
    ϑi2c                        S SK Jr  S SKJr  S SK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JrJr  S S
KJr  \(       a  S SKJrJr  S SKJr  S SKJr  S SKJrJr  / r " S S\5      rg)    )annotations)TYPE_CHECKINGN)_C_ops)	framework)base)LayerHelper)signature_safe_contextmanager)in_dynamic_modein_dynamic_or_pir_modein_pir_mode)	Optimizer)	GeneratorSequence)Tensor)_ParameterConfig)ExecutorProgramc                    ^  \ rS rSr% SrS\S'   S\S'   S\S'   S\S	'   S
\S'   S\S'   S\S'       S           SU 4S jjjrS rS r\	R                     S         SS jj5       r\R                  \	R                  SS j5       5       r\\	R                   S     SS jj5       5       r\	R                  S S!S jj5       rS rS rSrU =r$ )"ModelAverage*   a  
The ModelAverage optimizer accumulates specific continuous historical
parameters during training. The accumulated historical range can be controlled
by the passed ``average_window_rate`` argument. The averaged ``Parameter`` are
used in the prediction, which usually can improve the accuracy of the prediction.

Accumulate the average of the ``Parameter`` in the sliding window, the result will be saved
in a temporary variable, can be applied to the current model's ``Parameter`` by calling
the ``apply()`` method, and the current model ``Parameter`` can be restored by calling
the ``restore()`` method.

The window size for calculating the average is determined by ``average_window_rate``,
``min_average_window``, ``max_average_window`` and the current ``Parameter`` update times (num_updates).

When the cumulative times (num_accumulates) is greater than the specific window
threshold (average_window), the accumulated ``Parameter`` temporary variable is set to 0.0.
The following example will help to understand the role of these arguments:

::

    if num_accumulates >= min_average_window and num_accumulates >= min(max_average_window, num_updates * average_window_rate):
        num_accumulates = 0

In the above conditional judgment statement, ``num_accumulates`` indicates the current
accumulated number, which can be abstractly understood as the length of the cumulative window.
The length of the window must be at least the length set by the ``min_average_window`` argument,
and cannot exceed the length specified by the ``max_average_window`` argument or
``num_updates * average_window_rate``, where ``num_updates`` indicates the current ``Parameter``
update times, ``average_window_rate`` is a coefficient that calculates the length of the window.

Args:
    average_window_rate (float): The calculate ratio of the window length relative to ``Parameter`` update times.
    parameters (list, optional): List of ``Tensor`` names to update to minimize ``loss``. \
        This parameter is required in dygraph mode. \
        The default value is None in static graph mode, at this time all parameters will be updated.
    min_average_window (int, optional): the minimum size of average window length. The default value is 10000.
    max_average_window (int, optional): The maximum size of average window length. The default value is 10000.
    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

        >>> # doctest: +SKIP("Cannot get source code by to_static in REPL")
        >>> import numpy as np
        >>> import paddle
        >>> import paddle.nn as nn
        >>> import paddle.optimizer as opt

        >>> BATCH_SIZE = 16
        >>> BATCH_NUM = 4
        >>> EPOCH_NUM = 4

        >>> IMAGE_SIZE = 784
        >>> CLASS_NUM = 10

        >>> # define a random dataset
        >>> class RandomDataset(paddle.io.Dataset): # type: ignore[type-arg]
        ...     def __init__(self, num_samples):
        ...         self.num_samples = num_samples
        ...     def __getitem__(self, idx):
        ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
        ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
        ...         return image, label
        ...     def __len__(self):
        ...         return self.num_samples
        ...
        >>> class LinearNet(nn.Layer):
        ...     def __init__(self):
        ...         super().__init__()
        ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
        ...         self.bias = self._linear.bias
        ...
        ...     @paddle.jit.to_static
        ...     def forward(self, x):
        ...         return self._linear(x)
        ...
        >>> def train(layer, loader, loss_fn, opt, model_average):
        ...     for epoch_id in range(EPOCH_NUM):
        ...         for batch_id, (image, label) in enumerate(loader()):
        ...             out = layer(image)
        ...             loss = loss_fn(out, label)
        ...             loss.backward()
        ...             opt.step()
        ...             model_average.step()
        ...             opt.clear_grad()
        ...             model_average.clear_grad()
        ...             print("Train Epoch {} batch {}: loss = {}, bias = {}".format(
        ...                 epoch_id, batch_id, np.mean(loss.numpy()), layer.bias.numpy()))
        ...
        >>> def evaluate(layer, loader, loss_fn):
        ...     for batch_id, (image, label) in enumerate(loader()):
        ...         out = layer(image)
        ...         loss = loss_fn(out, label)
        ...         loss.backward()
        ...         print("Evaluate batch {}: loss = {}, bias = {}".format(
        ...             batch_id, np.mean(loss.numpy()), layer.bias.numpy()))
        ...
        >>> # create network
        >>> layer = LinearNet()
        >>> loss_fn = nn.CrossEntropyLoss()
        >>> optimizer = opt.Momentum(learning_rate=0.2, momentum=0.1, parameters=layer.parameters())
        >>> model_average = paddle.incubate.ModelAverage(
        ...     0.15,
        ...     parameters=layer.parameters(),
        ...     min_average_window=2,
        ...     max_average_window=10
        ... )
        ...
        >>> # create data loader
        >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
        >>> loader = paddle.io.DataLoader(dataset,
        ...     batch_size=BATCH_SIZE,
        ...     shuffle=True,
        ...     drop_last=True,
        ...     num_workers=2)
        ...
        >>> # create data loader
        >>> eval_loader = paddle.io.DataLoader(dataset,
        ...     batch_size=BATCH_SIZE,
        ...     shuffle=True,
        ...     drop_last=True,
        ...     num_workers=1
        ... )
        ...
        >>> # train
        >>> train(layer, loader, loss_fn, optimizer, model_average)

        >>> print("\nEvaluate With ModelAverage")
        >>> with model_average.apply(need_restore=False):
        ...     evaluate(layer, eval_loader, loss_fn)

        >>> print("\nEvaluate With Restored Parameters")
        >>> model_average.restore()
        >>> evaluate(layer, eval_loader, loss_fn)

r   helperfloataverage_windowintmin_average_windowmax_average_windowstrtyper   apply_programrestore_programc                  > [         T
U ]  SUS S US9  [        U R                  R                  5      U l        Xl        X0l        X@l        SU l	        [        5       (       Gd  [        R                  R                  5       R                  5       nU(       a  UOUR                  5       nU R!                  Xg5        U H  nU R#                  XhS /5        M     [        R                  R%                  5       U l        U R&                  R                  5       n	[        R                  R)                  U R&                  S9   U H  nU R+                  X5        M     S S S 5        [        R                  R%                  5       U l        U R,                  R                  5       n	[        R                  R)                  U R,                  S9   U H  nU R/                  X5        M     S S S 5        g g ! , (       d  f       N= f! , (       d  f       g = f)Ng        )learning_rate
parametersweight_decay	grad_clipnameaverage_accumulates)main_program)super__init__r   	__class____name__r   r   r   r   r   r
   paddlestaticdefault_main_programglobal_blockall_parameters_create_accumulators_append_optimize_opr   r   program_guard_add_average_apply_opr    _add_average_restore_op)selfaverage_window_rater#   r   r   r&   r0   r1   paramblockr+   s             f/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/incubate/optimizer/modelaverage.pyr*   ModelAverage.__init__   s    	! 	 	
 "$.."9"9:1"4"4)	  !====?LLNL(
l.I.I.K  %%lC'((t}E (!'!6!6!8D&&335E,,$:L:L,M+E..u< , N $*==#8#8#:D ((557E,,$:N:N,O+E00> , PO! ! NM
 POs   6G"=G3"
G03
Hc                   [        U[        R                  [        R                  R                  45      (       d   eU H  nU R                  SU5        U R                  SU5        U R                  SU5        U R                  SU5        U R                  SUSS/S9  U R                  S	USS/S9  U R                  S
USS/S9  M     g )Nsum_1sum_2sum_3restorenum_accumulatesint64   )dtypeshapeold_num_accumulatesnum_updates)
isinstancer   Blockr-   pir_add_accumulator)r7   r:   r#   r9   s       r;   r2   !ModelAverage._create_accumulators   s    %)//6::3C3C!DEEEEE!!'51!!'51!!'51!!)U3!!!5s "  !!%uGA3 "  !!uGA3 "       c                   [        U[        R                  [        R                  R                  45      (       d   eU R                  SUS   5      nU R                  SUS   5      nU R                  SUS   5      nU R                  SUS   5      nU R                  SUS   5      nU R                  SUS   5      n[        5       (       aH  [        R                  " US   UUUUUUU R                  U R                  U R                  5
      u            n	g [        R                  " 5       R                  5       nU R                  U R                  U R                  S.n
US   UUUUUUS	.nUUUUUUS
.nUR                  U R                  UUU
SS9nU$ )Nr>   r   r?   r@   rB   rG   rH   )r   r   r   )r9   in_sum_1in_sum_2in_sum_3in_num_accumulatesin_old_num_accumulatesin_num_updates)	out_sum_1	out_sum_2	out_sum_3out_num_accumulatesout_old_num_accumulatesout_num_updatesT)r   inputsoutputsattrsstop_gradient)rI   r   rJ   r-   rK   _get_accumulatorr   r   average_accumulates_r   r   r   r/   r0   	append_opr   )r7   r:   param_and_gradr>   r?   r@   rB   rG   rH   _r^   r\   r]   average_accumulates_ops                 r;   r3    ModelAverage._append_optimize_op   s   %)//6::3C3C!DEEEE%%g~a/@A%%g~a/@A%%g~a/@A//~a0
 #33!>!#4
 ++M>!;LM!##%::q!###'''' Aq!Q1 ..0==?"11"&"9"9"&"9"9
 $A&"1&9)
 #2':*
 "' "1 "
 &%rN   c                D    [        5       (       a  U R                  5         gg)a^  
Add operations to minimize ``loss`` by updating ``parameters``.

Args:
    loss (Tensor): A ``Tensor`` containing the value to minimize.
    startup_program (Program, optional): :ref:`api_paddle_static_Program` for
        initializing parameters in ``parameters``. The default value
        is None, at this time :ref:`api_paddle_static_default_startup_program` will be used.
    parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update
        to minimize ``loss``. The default value is None, at this time all parameters
        will be updated.
    no_grad_set (set, optional): Set of ``Tensor``  or ``Tensor.name`` that don't need
        to be updated. The default value is None.

Returns:
    tuple: tuple (optimize_ops, params_grads), A list of operators appended
    by minimize and a list of (param, grad) tensor pairs, param is
    ``Parameter``, grad is the gradient value corresponding to the parameter.
    In static graph mode, the returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to
    indicate program pruning. If so, the program will be pruned by ``feed`` and
    ``fetch_list`` before run, see details in ``Executor``.

Examples:

    .. code-block:: python

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

        >>> sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters())
        >>> sgd.minimize(loss)

        >>> modelaverage = paddle.incubate.ModelAverage(
        ...     0.15,
        ...     parameters=linear.parameters(),
        ...     min_average_window=2,
        ...     max_average_window=4
        ... )
        >>> modelaverage.minimize(loss)
        >>> sgd.clear_grad()
        >>> modelaverage.clear_grad()

N)r
   step)r7   lossstartup_programr#   no_grad_sets        r;   minimizeModelAverage.minimize<  s    n IIK rN   c                n   / nU R                    HK  nUR                  (       d  M  UR                  5       c  M)  UR                  5       nUR                  X#45        MM     [        R
                  " 5       R                  5       nU R                  X@R                   5        U H  nU R                  XE5        M     g)a  
Execute the optimizer and update parameters once.

Returns:
    None

Examples:

    .. code-block:: python

        >>> import paddle
        >>> inp = paddle.rand([1, 10], dtype="float32")
        >>> linear = paddle.nn.Linear(10, 1)
        >>> out = linear(inp)
        >>> loss = paddle.mean(out)
        >>> sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters())
        >>> modelaverage = paddle.incubate.ModelAverage(
        ...     0.15,
        ...     parameters=linear.parameters(),
        ...     min_average_window=2,
        ...     max_average_window=4
        ... )
        >>> loss.backward()
        >>> sgd.step()
        >>> modelaverage.step()
        >>> sgd.clear_grad()
        >>> modelaverage.clear_grad()
N)	_parameter_list	trainable
_grad_ivarappendr   r/   r0   r2   r3   )r7   params_gradsr9   grad_varr:   rc   s         r;   rh   ModelAverage.stepv  s    @ ))E??!- ++-##U$56 * ..0==?!!%)=)=>*N$$U; +rN   c              #  2  #    [        5       (       Ga  U R                   H  nU R                  SU5      nU R                  SU5      nU R                  SU5      nU R                  SU5      nU R                  SU5      nU R                  SU5      n	[        R                  " X95        Xg-   U-   n
XE-   n[        R
                  " U
SS9n
[        R
                  " USS9nX-  n[        R                  " X5        M      S	v   U(       a  U R                  5         g	Uc  [        S
5      eUR                  U R                  5         S	v   U(       a  U R                  U5        g	g	! U(       a  U R                  5         f f = f! U(       a  U R                  U5        f f = f7f)a  
Apply the average of the cumulative ``Parameter`` to the parameters of the current model.

Args:
    executor(Executor): The network executor in static-graph mode. The default value is None in dygraph mode.
    need_restore(bool): Restore flag variable, if set to True, the network will restore
        the parameters of the network to the default value, if set to False,
        it will not be restored. The default value is True.

Examples:

    .. code-block:: python

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

        >>> sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters())

        >>> modelaverage = paddle.incubate.ModelAverage(
        ...     0.15,
        ...     parameters=linear.parameters(),
        ...     min_average_window=2,
        ...     max_average_window=4
        ... )
        >>> sgd.step()
        >>> modelaverage.step()

        >>> with modelaverage.apply():
        ...     for param in linear.parameters():
        ...         print(param)

        >>> for param in linear.parameters():
        ...     print(param)
rB   rG   r>   r?   r@   rA   float32)rE   N1Executor should not be None in static graph mode.)
r
   ro   r`   r-   assigncastrA   RuntimeErrorrunr   )r7   executorneed_restorer9   rB   rG   r>   r?   r@   param_restoretotal_paramtotal_accumulatesaverage_params                r;   applyModelAverage.apply  s{    V --"&"7"7%u# '+&;&;)5'# --gu=--gu=--gu= $ 5 5i Ge3#me3$3$I!$kk+YG$*KK%Y%! !, ?m3) .*#LLNC  	T''(	'X&   LLN   X& s7   C5F8E <AF>E9 FE66F9FFc                    [        5       (       a<  U R                   H+  nU R                  SU5      n[        R                  " X25        M-     gUc  [        S5      eUR                  U R                  5        g)a\  
Restore ``Parameter`` values of current model.

Args:
    executor(Executor): The network executor in static-graph mode. The default value is None in dygraph mode

Examples:

    .. code-block:: python

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

        >>> sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters())

        >>> modelaverage = paddle.incubate.ModelAverage(
        ...     0.15,
        ...     parameters=linear.parameters(),
        ...     min_average_window=2,
        ...     max_average_window=4
        ... )
        >>> sgd.step()
        >>> modelaverage.step()

        >>> with modelaverage.apply(need_restore=False):
        ...     for param in linear.parameters():
        ...         print(param)

        >>> for param in linear.parameters():
        ...     print(param)

        >>> modelaverage.restore()

        >>> for param in linear.parameters():
        ...     print(param)
rA   Nrx   )r
   ro   r`   r-   ry   r{   r|   r    )r7   r}   r9   r   s       r;   rA   ModelAverage.restore  sk    T -- $ 5 5i Gm3 . C  	T))*rN   c                   [        5       (       Ga  [        R                  R                  5       n[        R                  R
                  R                  X25      nU R                  SU5      n[        R                  R
                  R                  X45      nU R                  SU5      n[        R                  R
                  R                  X65      nU R                  SU5      n[        R                  R
                  R                  X75      nU R                  SU5      n[        R                  R
                  R                  X85      nU R                  SU5      n	[        R                  R
                  R                  X95      n	U R                  SU5      n
[        R                  R
                  R                  X:5      n
OUR                  U5      nUR                  U R                  SU5      5      nUR                  U R                  SU5      5      nUR                  U R                  SU5      5      nUR                  U R                  SU5      5      nUR                  U R                  SU5      5      n	UR                  U R                  SU5      5      n
[        R                  " X%S9  [        R                  " X/5      n[        R                  " XgU/5      n[        R                  " XR                  c  SOU R                  S	9n[        R                  " XR                  c  SOU R                  S	9n[        R                  " XS
9n[        R                  " XS9  g )NrA   r>   r?   r@   rB   rG   outputrw   )xrE   )r   y)r   r-   r.   r/   rK   core_get_parameterr`   _get_persistable_value_clone_variablery   add_nrz   _dtypedivide)r7   r:   r9   target_programrestore_valuegradr>   r?   r@   rB   rG   tmpsum
divide_outs                 r;   r5   "ModelAverage._add_average_apply_op*  s   ==#]]??ANJJOO22>IE 11)UCM::??99D ))'59EJJOO::E ))'59EJJOO::E ))'59EJJOO::E #334EuMO$jjooDDO #'"7"7%u# #)**//"H"H# ))%0E((%%i7D ))$*?*?*OPE))$*?*?*OPE))$*?*?*OPE#33%%&7?O #("7"7%%&;UC# 	e)llOABllE%01kkkk&9t{{
 kkkk&9t{{
 ]]S0
j/rN   c                   [        5       (       a  [        R                  R                  5       n[        R                  R
                  R                  X25      nU R                  SU5      n[        R                  R
                  R                  X45      nO2UR                  U5      nUR                  U R                  SU5      5      n[        R                  " XRS9  g )NrA   r   )r   r-   r.   r/   rK   r   r   r`   r   r   ry   )r7   r:   r9   r   r   r   s         r;   r6   $ModelAverage._add_average_restore_opd  s    ==#]]??ANJJOO22>IE 11)UCM::??99D ))%0E((%%i7D 	d)rN   )r   r   r   r   r   r    r   )N'  r   N)r8   r   r#   z4Sequence[Tensor] | Sequence[_ParameterConfig] | Noner   r   r   r   r&   z
str | NonereturnNone)NNN)
ri   r   rj   zProgram | Noner#   zlist[Tensor] | Nonerk   zset[Tensor] | set[str] | Noner   r   )r   r   )NT)r}   Executor | Noner~   boolr   zGenerator[None, None, None])N)r}   r   r   r   )r,   
__module____qualname____firstlineno____doc____annotations__r*   r2   r3   imperative_baseno_gradrl   r   dygraph_onlyrh   r	   r   rA   r5   r6   __static_attributes____classcell__)r+   s   @r;   r   r   *   s   JX 
I
 LP"'"'(?"(? I(?  	(?
  (? (? 
(? (?T$?&B  +/*.5977 (7 (	7
 37 
7 7r )<  )<V #EIN''N'>BN'	$N'  #N'` 2+ 2+h80t* *rN   r   ) 
__future__r   typingr   r-   r   paddle.baser   paddle.base.dygraphr   r   paddle.base.layer_helperr   paddle.base.wrapped_decoratorr	   paddle.frameworkr
   r   r   paddle.optimizerr   collections.abcr   r   r   paddle.optimizer.optimizerr   paddle.staticr   r   __all__r    rN   r;   <module>r      sR    #     ! 7 0 G 
 '3;/ G	*9 G	*rN   