
    zj                       U d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlZ	d dl
Z
d dlmZ ddlmZ erGd dlmZmZmZ d dlmZmZ d d	lmZ dd
lmZ ed         Zded<    G d de          Z G d de          Zg Z	 	 	 	 	 	 	 	 	 	 	 d:d;d(Z G d) d'          Z G d* d+          Z  G d, d-e           Z! G d. d/e           Z" G d0 d1e           Z# G d2 d3e           Z$ G d4 d5e           Z% G d6 d7e           Z& G d8 d9e           Z'dS )<    )annotationsN)TYPE_CHECKING)
try_import   )ProgressBar)AnyLiteral	TypedDict)IteratorSequence)	TypeAlias)Modeltrainevalpredictr   _CallbackModec                  B    e Zd ZU ded<   ded<   ded<   ded<   ded<   dS )	_CallbackParamsint
batch_sizeepochsstepsverbose	list[str]metricsN__name__
__module____qualname____annotations__     e/lsinfo/ai/hellotax_ai/data_center/backend/venv/lib/python3.11/site-packages/paddle/hapi/callbacks.pyr   r   '   sB         


r#   r   c                  .    e Zd ZU ded<   ded<   ded<   dS )_CallbackLogsfloatlossr   r   r   r   Nr   r"   r#   r$   r&   r&   .   s.         r#   r&      r   	callbacks$Sequence[Callback] | Callback | NonemodelModel | Noner   
int | Noner   r   log_freqr   r   	save_freqsave_dir
str | Noner   list[str] | NonemodeLiteral['train', 'test']returnCallbackListc                T   | pg }t          t          |t           t          f          r|n|g          }t          d |D                       s|rt	          ||          g|}t          d |D                       sg |t          ||          }|D ]}t          |t                    r||_        t          d |D                       sg |t                      }t          |          }|
                    |           |
dk    r|	pg ng }	|||||	d}|                    |           |S )Nc              3  @   K   | ]}t          |t                    V  d S N)
isinstanceProgBarLogger.0ks     r$   	<genexpr>z#config_callbacks.<locals>.<genexpr>H   s,      ::z!]++::::::r#   )r   c              3  @   K   | ]}t          |t                    V  d S r:   )r;   ModelCheckpointr=   s     r$   r@   z#config_callbacks.<locals>.<genexpr>K   s,      <<!z!_--<<<<<<r#   c              3  @   K   | ]}t          |t                    V  d S r:   )r;   LRSchedulerr=   s     r$   r@   z#config_callbacks.<locals>.<genexpr>Q   s,      88az![))888888r#   test)r   r   r   r   r   )listr;   tupleanyr<   rB   EarlyStoppingr1   rD   r7   	set_model
set_params)r*   r,   r   r   r   r/   r   r0   r1   r   r4   _cbkscbksr?   cbk_listparamss                   r$   config_callbacksrP   7   sz    OEED%=11>w D ::T::::: Aw Ah888@4@<<t<<<<< =<<y(;;< " "a'' 	"!AJ88488888 &%%{}}%D!!Hu#v~~gm2G  F Or#   c                      e Zd Zd%d&dZd'd	Zd(dZd)dZd*dZd+dZd,dZ		 d%d-dZ
	 d%d-dZ	 d.d/d Z	 d.d/d!Z	 	 d.d0d#Z	 	 d.d0d$ZdS )1r7   Nr*   Sequence[Callback] | Noner6   Nonec                R    |J t          |          | _        i | _        d | _        d S r:   )rF   r*   rO   r,   )selfr*   s     r$   __init__zCallbackList.__init__c   s-    $$$i


r#   callbackCallbackc                :    | j                             |           d S r:   )r*   append)rU   rW   s     r$   rZ   zCallbackList.appendj   s    h'''''r#   Iterator[Callback]c                *    t          | j                  S r:   )iterr*   rU   s    r$   __iter__zCallbackList.__iter__m   s    DN###r#   rO   r   c                D    | j         D ]}|                    |           d S r:   )r*   rK   )rU   rO   cs      r$   rK   zCallbackList.set_paramsp   s2     	! 	!ALL    	! 	!r#   r,   r   c                D    | j         D ]}|                    |           d S r:   )r*   rJ   )rU   r,   ra   s      r$   rJ   zCallbackList.set_modelt   s2     	 	AKK	 	r#   namestrargsr   c                D    | j         D ]}t          ||          } ||  d S r:   )r*   getattr)rU   rc   re   ra   funcs        r$   _callzCallbackList._callx   s9     	 	A1d##DD$KKK	 	r#   r4   r   c                "    |dv s
J d            d S )Nr   z%mode should be train, eval or predictr"   )rU   r4   s     r$   _check_modezCallbackList._check_mode}   s7     
 
 
 
 3	
 
 
 
 
r#   logs_CallbackLogs | Nonec                h    |                      |           d| d}|                     ||           d S )Non__beginrk   ri   rU   r4   rl   rc   s       r$   on_beginzCallbackList.on_begin   sB     	!T!!!

4r#   c                h    |                      |           d| d}|                     ||           d S )Nro   _endrq   rr   s       r$   on_endzCallbackList.on_end   sB     	T

4r#   epochr.   c                4    |                      d||           d S )Non_epoch_beginri   rU   rw   rl   s      r$   ry   zCallbackList.on_epoch_begin   s!     	

#UD11111r#   c                4    |                      d||           d S )Non_epoch_endrz   r{   s      r$   r}   zCallbackList.on_epoch_end   s      	

>5$/////r#   stepc                j    |                      |           d| d}|                     |||           d S )Nro   _batch_beginrq   rU   r4   r~   rl   rc   s        r$   on_batch_beginzCallbackList.on_batch_begin   sD     	'T'''

4t$$$$$r#   c                j    |                      |           d| d}|                     |||           d S )Nro   
_batch_endrq   r   s        r$   on_batch_endzCallbackList.on_batch_end   sD     	%T%%%

4t$$$$$r#   r:   )r*   rR   r6   rS   )rW   rX   r6   rS   )r6   r[   rO   r   r6   rS   r,   r   r6   rS   )rc   rd   re   r   r6   rS   )r4   r   r6   rS   )r4   r   rl   rm   r6   rS   NNrw   r.   rl   rm   r6   rS   )r4   r   r~   r.   rl   rm   r6   rS   )r   r   r    rV   rZ   r_   rK   rJ   ri   rk   rs   rv   ry   r}   r   r   r"   r#   r$   r7   r7   b   sg           ( ( ( ($ $ $ $! ! ! !      
3 3 3 3 AE     AE     FJ2 2 2 2 2 FJ0 0 0 0 0  %)	% % % % %  %)	% % % % % % %r#   c                      e Zd ZU dZded<   ded<   d dZd!d	Zd"dZd#d$dZd#d$dZ	d#d$dZ
d#d$dZd#d$dZd#d$dZ	 d#d%dZ	 d#d%dZ	 d#d&dZ	 d#d&dZ	 d#d&dZ	 d#d&dZ	 d#d&dZ	 d#d&dZdS )'rX   ad  
    Base class used to build new callbacks. And new callbacks could also
    terminate training by setting `model.stop_training=True`.

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> # build a simple model checkpoint callback
            >>> class ModelCheckpoint(paddle.callbacks.Callback):
            ...     def __init__(self, save_freq=1, save_dir=None):
            ...         self.save_freq = save_freq
            ...         self.save_dir = save_dir
            ...
            ...     def on_epoch_end(self, epoch, logs=None):
            ...         if self.model is not None and epoch % self.save_freq == 0:
            ...             path = '{}/{}'.format(self.save_dir, epoch)
            ...             print('save checkpoint at {}'.format(path))
            ...             self.model.save(path)

    r-   r,   r   rO   r6   rS   c                "    d | _         i | _        d S r:   )r,   rO   r^   s    r$   rV   zCallback.__init__   s    
r#   c                    || _         dS )a  
        Set parameters, which is dict. The keys contain:

          - 'batch_size': an integer. Number of samples per batch.
          - 'epochs': an integer. Number of epochs.
          - 'steps': an integer. Number of steps of one epoch.
          - 'verbose': an integer. Verbose mode is 0, 1 or 2. 0 = silent, 1 = progress bar, 2 = one line per epoch.
          - 'metrics': a list of str. Names of metrics, including 'loss' and the names of paddle.metric.Metric.
        N)rO   )rU   rO   s     r$   rK   zCallback.set_params   s     r#   r   c                    || _         dS )z"model is instance of paddle.Model.N)r,   )rU   r,   s     r$   rJ   zCallback.set_model   s    


r#   Nrl   rm   c                    dS )zmCalled at the start of training.

        Args:
            logs (dict): The logs is a dict or None.
        Nr"   rU   rl   s     r$   on_train_beginzCallback.on_train_begin         r#   c                    dS )zCalled at the end of training.

        Args:
            logs (dict): The logs is a dict or None. The keys of logs
                passed by paddle.Model contains 'loss', metric names and
                `batch_size`.
        Nr"   r   s     r$   on_train_endzCallback.on_train_end   r   r#   c                    dS )a  Called at the start of evaluation.

        Args:
            logs (dict): The logs is a dict or None. The keys of logs
                passed by paddle.Model contains 'steps' and 'metrics',
                The `steps` is number of total steps of validation dataset.
                The `metrics` is a list of str including 'loss' and the names
                of paddle.metric.Metric.
        Nr"   r   s     r$   on_eval_beginzCallback.on_eval_begin   r   r#   c                    dS )a  Called at the end of evaluation.

        Args:
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is a dict contains 'loss', metrics and 'batch_size'
                of last batch of validation dataset.
        Nr"   r   s     r$   on_eval_endzCallback.on_eval_end   r   r#   c                    dS )zpCalled at the beginning of predict.

        Args:
            logs (dict): The logs is a dict or None.
        Nr"   r   s     r$   on_predict_beginzCallback.on_predict_begin  r   r#   c                    dS )zjCalled at the end of predict.

        Args:
            logs (dict): The logs is a dict or None.
        Nr"   r   s     r$   on_predict_endzCallback.on_predict_end  r   r#   rw   r   c                    dS )zCalled at the beginning of each epoch.

        Args:
            epoch (int): The index of epoch.
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is None.
        Nr"   r{   s      r$   ry   zCallback.on_epoch_begin  r   r#   c                    dS )a   Called at the end of each epoch.

        Args:
            epoch (int): The index of epoch.
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is a dict, contains 'loss', metrics and 'batch_size'
                of last batch.
        Nr"   r{   s      r$   r}   zCallback.on_epoch_end  r   r#   r~   c                    dS )zCalled at the beginning of each batch in training.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is empty.
        Nr"   rU   r~   rl   s      r$   on_train_batch_beginzCallback.on_train_batch_begin*  r   r#   c                    dS )a<  Called at the end of each batch in training.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is a dict, contains 'loss', metrics and 'batch_size'
                of current batch.
        Nr"   r   s      r$   on_train_batch_endzCallback.on_train_batch_end5  r   r#   c                    dS )zCalled at the beginning of each batch in evaluation.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is empty.
        Nr"   r   s      r$   on_eval_batch_beginzCallback.on_eval_batch_beginA  r   r#   c                    dS )a>  Called at the end of each batch in evaluation.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None. The `logs` passed by
                paddle.Model is a dict, contains 'loss', metrics and 'batch_size'
                of current batch.
        Nr"   r   s      r$   on_eval_batch_endzCallback.on_eval_batch_endL  r   r#   c                    dS )zCalled at the beginning of each batch in predict.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None.
        Nr"   r   s      r$   on_predict_batch_beginzCallback.on_predict_batch_beginX  r   r#   c                    dS )zCalled at the end of each batch in predict.

        Args:
            step (int): The index of step (or iteration).
            logs (dict): The logs is a dict or None.
        Nr"   r   s      r$   on_predict_batch_endzCallback.on_predict_batch_endb  r   r#   r6   rS   r   r   r:   rl   rm   r6   rS   rw   r   rl   rm   r6   rS   r~   r   rl   rm   r6   rS   )r   r   r    __doc__r!   rV   rK   rJ   r   r   r   r   r   r   ry   r}   r   r   r   r   r   r   r"   r#   r$   rX   rX      s         0    
 
 
 
           	 	 	 	 	             8<	 	 	 	 	 8<
 
 
 
 
 7;	 	 	 	 	 7;
 
 
 
 
 7;	 	 	 	 	 7;
 
 
 
 
 7;     7;      r#   rX   c                      e Zd ZU dZded<   ded<   ded<   ded<   ded	<   d%d&dZd Zd'd(dZ	 d)d*dZd+dZ		 d'd,dZ
	 d'd,dZ	 d'd-dZd'd(dZ	 d'd,dZ	 d'd,dZd'd(d Z	 d'd,d!Z	 d'd,d"Zd'd(d#Zd'd(d$ZdS ).r<   a  
    Logger callback function to print loss and metrics to stdout. It supports
    silent mode (not print), progress bar or one line per each printing,
    see arguments for more detailed.

    Args:
        log_freq (int): The frequency, in number of steps,
            the logs such as loss, metrics are printed. Default: 1.
        verbose (int): The verbosity mode, should be 0, 1, or 2.
            0 = silent, 1 = progress bar, 2 = one line each printing, 3 = 2 +
            time counter, such as average reader cost, samples per second.
            Default: 2.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.vision.transforms as T
            >>> from paddle.vision.datasets import MNIST
            >>> from paddle.static import InputSpec

            >>> inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> transform = T.Compose([
            ...     T.Transpose(),
            ...     T.Normalize([127.5], [127.5])
            ... ])
            >>> train_dataset = MNIST(mode='train', transform=transform)

            >>> lenet = paddle.vision.models.LeNet()
            >>> model = paddle.Model(lenet,
            ...     inputs, labels)

            >>> optim = paddle.optimizer.Adam(0.001, parameters=lenet.parameters())
            >>> model.prepare(optimizer=optim,
            ...             loss=paddle.nn.CrossEntropyLoss(),
            ...             metrics=paddle.metric.Accuracy())

            >>> callback = paddle.callbacks.ProgBarLogger(log_freq=10)
            >>> model.fit(train_dataset, batch_size=64, callbacks=callback)
    r.   r   r   zProgressBar | Noneprogbarr   r   r/   r   r)   r6   rS   c                L    d | _         d | _        d | _        || _        || _        d S r:   )r   r   r   r   r/   )rU   r/   r   s      r$   rV   zProgBarLogger.__init__  s)    
 r#   c                ^    | j         o&t          j                                        j        dk    S Nr   )r   paddledistributedParallelEnv
local_rankr^   s    r$   	_is_printzProgBarLogger._is_print  s&    |P 2 > > @ @ Kq PPr#   Nrl   rm   c                    | j         d         | _        | j        sJ | j         d         | _        | j        sJ ddddd| _        |                                 rt          d           d S d S )Nr   r   r   	data_time
batch_timecountsampleszmThe loss value printed in the log is the current step, and the metric is the average value of previous steps.)rO   r   train_metrics_train_timerr   printr   s     r$   r   zProgBarLogger.on_train_begin  s    k(+{{![3!!!! 	
 
 >> 	    	 	r#   rw   c                ,   | j         d         | _        || _        d| _        | j        r1|                                 rt          d|dz    d| j                    t          | j        | j                  | _	        t          j
                    | j        d<   d S )Nr   r   Epoch r   /numr   batch_start_time)rO   r   rw   
train_stepr   r   r   r   r   train_progbartimer   r{   s      r$   ry   zProgBarLogger.on_epoch_begin  s     [)

; 	64>>++ 	6451944t{44555(TZNNN04	,---r#   r4   r   c                   g }t          | | d          }t          | | d          }t          | | d          }|D ]#}||v r|                    |||         f           $| j        dk    rt          | d| d          rt          | d| d          }|d         dk    r|d         nd	}	|d
         dk    r|d
         nd	}
|                    dd|d         |	z  z  f           |                    dd|d         |	z  z  f           |                    dd|
|d         |d         z   z  z  f           d|d<   d|d
<   d|d<   d|d<   |                    ||           d S )N_metrics_progbar_step   __timerr   r         ?r   avg_reader_costz%.5f secr   avg_batch_costr   ipsz%.5f samples/secg        )rg   rZ   r   hasattrupdate)rU   rl   r4   valuesr   r   r   r?   timercntr   s              r$   _updateszProgBarLogger._updates  s   $4 1 1 122$4 1 1 122nnn-- 	, 	,ADyyq$q'l+++<1/?4/?/?/?!@!@D"2d"2"2"233E$)'NQ$6$6%..CC*/	*:Q*>*>eI&&CGMM"J%2Ds2J$KL   MM!:|1Ds1J#KL   MM&%"4u\7J"JKM   E'N E)!$E+"%E,uf%%%%%r#   r~   c                    t          j                     | j        d<   | j        dxx         | j        d         | j        d         z
  z  cc<   d S Nbatch_data_end_timer   r   )r   r   r   s      r$   r   z"ProgBarLogger.on_train_batch_begin  sZ     489;;/0+&&&34 234	
&&&&&r#   c                   |pi }| xj         dz  c_         | j        dxx         t          j                    | j        d         z
  z  cc<   | j        dxx         dz  cc<   |                    dd          }| j        dxx         |z  cc<   |                                 r@| j         | j        z  dk    r-| j        | j         | j        k     r|                     |d           t          j                    | j        d	<   d S )
Nr   r   r   r   r   r   r   r   r   )r   r   r   getr   r/   r   r   rU   r~   rl   r   s       r$   r   z ProgBarLogger.on_train_batch_end  s    zr1,'''IKK$+,ABB	
''' 	'"""a'"""((<++)$$$/$$$>> 	-$- ?1 D Dz!T_tz%A%AdG,,,04	,---r#   c                x    |pi }|                                  r| j        |                     |d           d S d S d S )Nr   )r   r   r   r{   s      r$   r}   zProgBarLogger.on_epoch_end  sP     zr>> 	)!7MM$(((((	) 	)!7!7r#   c                b   |                     dd           | _        |                     dg           | _        d| _        d| _        ddddd| _        t          | j        | j                  | _        | 	                                rt          d           t          j                    | j        d<   d S )Nr   r   r   r   r   zEval begin...r   )r   
eval_stepseval_metrics	eval_stepevaled_samples_eval_timerr   r   eval_progbarr   r   r   r   s     r$   r   zProgBarLogger.on_eval_begin	  s    ((7D11 HHY33 	
 
 (
 
 
 >> 	#/"""/3y{{+,,,r#   c                    t          j                     | j        d<   | j        dxx         | j        d         | j        d         z
  z  cc<   d S r   )r   r   r   s      r$   r   z!ProgBarLogger.on_eval_batch_begin  Z     37)++./%%%23123	
%%%%%r#   c                @   |pi }| xj         dz  c_         |                    dd          }| xj        |z  c_        | j        dxx         t	          j                    | j        d         z
  z  cc<   | j        dxx         dz  cc<   |                    dd          }| j        dxx         |z  cc<   |                                 r@| j         | j        z  dk    r-| j        | j         | j        k     r|                     |d           t	          j                    | j        d	<   d S )
Nr   r   r   r   r   r   r   r   r   )	r   r   r   r   r   r   r/   r   r   r   s       r$   r   zProgBarLogger.on_eval_batch_end'  s6    zr!((<++w&&&&IKK$*+@AA	
&&& 	!!!Q&!!!((<++###w.###>> 	, >! C C&$.4?*J*JdF+++/3y{{+,,,r#   c                b   |                     dd           | _        |                     dg           | _        d| _        d| _        ddddd| _        t          | j        | j                  | _        | 	                                rt          d           t          j                    | j        d<   d S )Nr   r   r   r   r   zPredict begin...r   )r   
test_stepstest_metrics	test_steptested_samples_test_timerr   r   test_progbarr   r   r   r   s     r$   r   zProgBarLogger.on_predict_begin<  s    ((7D11 HHY33 	
 
 (
 
 
 >> 	&$%%%/3y{{+,,,r#   c                    t          j                     | j        d<   | j        dxx         | j        d         | j        d         z
  z  cc<   d S r   )r   r   r   s      r$   r   z$ProgBarLogger.on_predict_batch_beginQ  r   r#   c                @   |pi }| xj         dz  c_         |                    dd          }| xj        |z  c_        | j        dxx         t	          j                    | j        d         z
  z  cc<   | j        dxx         dz  cc<   |                    dd          }| j        dxx         |z  cc<   | j         | j        z  dk    rA|                                 r-| j        | j         | j        k     r|                     |d           t	          j                    | j        d	<   d S )
Nr   r   r   r   r   r   r   rE   r   )	r   r   r   r   r   r/   r   r   r   r   s       r$   r   z"ProgBarLogger.on_predict_batch_endZ  s4    zr!((<++w&&&&IKK$*+@AA	
&&& 	!!!Q&!!!((<++###w.###>DM)Q..4>>3C3C.&$.4?*J*JdF+++/3y{{+,,,r#   c                    |pi }|                                  r6| j        1|                     |d           t          d| j                    d S d S d S )Nr   zEval samples: )r   r   r   r   r   r   s     r$   r   zProgBarLogger.on_eval_endo  sh    zr>> 	:!<MM$'''84#68899999	: 	:!<!<r#   c                    |pi }|                                  rM| j        | j        z  dk    s| j        dk    r|                     |d           t          d| j                    d S d S )Nr   r   rE   zPredict samples: )r   r   r/   r   r   r   r   r   s     r$   r   zProgBarLogger.on_predict_endu  s{    zr>> 	=~-22dla6G6GdF+++;d&9;;<<<<<	= 	=r#   )r   r)   )r/   r   r   r   r6   rS   r:   r   r   r   rl   rm   r4   r   r6   rS   r   r   )r   r   r    r   r!   rV   r   r   ry   r   r   r   r}   r   r   r   r   r   r   r   r   r"   r#   r$   r<   r<   m  s        ) )V LLLMMM! ! ! ! !Q Q Q    $ FJ
< 
< 
< 
< 
< &  &  &  &F 7;
 
 
 
 
 7;< < < < <$ 8<) ) ) ) ); ; ; ; ;, 7;
 
 
 
 
 7;; ; ; ; ;*; ; ; ; ;, 7;
 
 
 
 
 7;; ; ; ; ;*: : : : := = = = = = =r#   r<   c                  D    e Zd ZdZddd
Z	 dddZd Z	 dddZdddZdS )rB   ac  
    Model checkpoint callback function to save model weights and optimizer
    state during training in conjunction with model.fit(). Currently,
    ModelCheckpoint only supports saving after a fixed number of epochs.

    Args:
        save_freq(int): The frequency, in number of epochs, the model checkpoint
            are saved. Default: 1.
        save_dir(str|None): The directory to save checkpoint during training.
            If None, will not save checkpoint. Default: None.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.vision.transforms as T
            >>> from paddle.vision.datasets import MNIST
            >>> from paddle.static import InputSpec

            >>> inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> transform = T.Compose([
            ...     T.Transpose(),
            ...     T.Normalize([127.5], [127.5])
            ... ])
            >>> train_dataset = MNIST(mode='train', transform=transform)

            >>> lenet = paddle.vision.models.LeNet()
            >>> model = paddle.Model(lenet,
            ...     inputs, labels)

            >>> optim = paddle.optimizer.Adam(0.001, parameters=lenet.parameters())
            >>> model.prepare(optimizer=optim,
            ...             loss=paddle.nn.CrossEntropyLoss(),
            ...             metrics=paddle.metric.Accuracy())

            >>> callback = paddle.callbacks.ModelCheckpoint(save_dir='./temp')
            >>> model.fit(train_dataset, batch_size=64, callbacks=callback)
    r   Nr0   r   r1   r2   r6   rS   c                "    || _         || _        d S r:   )r0   r1   )rU   r0   r1   s      r$   rV   zModelCheckpoint.__init__  s    " r#   rw   r.   rl   rm   c                    || _         d S r:   )rw   r{   s      r$   ry   zModelCheckpoint.on_epoch_begin  s     


r#   c                l    | j         o-| j        o&t          j                                        j        dk    S r   )r,   r1   r   r   r   r   r^   s    r$   _is_savezModelCheckpoint._is_save  s7    J AA"..00;q@	
r#   c                   |                                  rj| j        | j        z  dk    rY| j         d| }t	          dt
          j                            |                      | j        	                    |           d S d S d S )Nr   r   save checkpoint at )
r   rw   r0   r1   r   ospathabspathr,   save)rU   rw   rl   r  s       r$   r}   zModelCheckpoint.on_epoch_end  s     ==?? 	"tzDN:a??m--e--D?(=(=??@@@JOOD!!!!!	" 	"??r#   c                    |                                  rU| j         d}t          dt          j                            |                      | j                            |           d S d S )Nz/finalr   )r   r1   r   r  r  r  r,   r  )rU   rl   r  s      r$   r   zModelCheckpoint.on_train_end  sk    ==?? 	"m+++D?(=(=??@@@JOOD!!!!!	" 	"r#   )r   N)r0   r   r1   r2   r6   rS   r   r   r:   r   r   )	r   r   r    r   rV   ry   r   r}   r   r"   r#   r$   rB   rB   }  s        ' 'R! ! ! ! !
 FJ    

 
 
 8<" " " " "" " " " " " "r#   rB   c                  4    e Zd ZdZddd	Z	 dddZ	 dddZd
S )rD   aj
  Lr scheduler callback function

    Args:
        by_step(bool, optional): whether to update learning rate scheduler
            by step. Default: True.
        by_epoch(bool, optional): whether to update learning rate scheduler
            by epoch. Default: False.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.vision.transforms as T
            >>> from paddle.static import InputSpec

            >>> inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> transform = T.Compose([
            ...     T.Transpose(),
            ...     T.Normalize([127.5], [127.5])
            ... ])
            >>> train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)

            >>> lenet = paddle.vision.models.LeNet()
            >>> model = paddle.Model(lenet,
            ...     inputs, labels)

            >>> base_lr = 1e-3
            >>> boundaries = [5, 8]
            >>> wamup_steps = 4

            >>> def make_optimizer(parameters=None):
            ...     momentum = 0.9
            ...     weight_decay = 5e-4
            ...     values = [base_lr * (0.1**i) for i in range(len(boundaries) + 1)]
            ...     learning_rate = paddle.optimizer.lr.PiecewiseDecay(
            ...         boundaries=boundaries, values=values)
            ...     learning_rate = paddle.optimizer.lr.LinearWarmup(
            ...         learning_rate=learning_rate,
            ...         warmup_steps=wamup_steps,
            ...         start_lr=base_lr / 5.,
            ...         end_lr=base_lr,
            ...         verbose=True)
            ...     optimizer = paddle.optimizer.Momentum(
            ...         learning_rate=learning_rate,
            ...         weight_decay=weight_decay,
            ...         momentum=momentum,
            ...         parameters=parameters)
            ...     return optimizer

            >>> optim = make_optimizer(parameters=lenet.parameters())
            >>> model.prepare(optimizer=optim,
            ...             loss=paddle.nn.CrossEntropyLoss(),
            ...             metrics=paddle.metric.Accuracy())

            >>> # if LRScheduler callback not set, an instance LRScheduler update by step
            >>> # will be created auto.
            >>> model.fit(train_dataset, batch_size=64)

            >>> # create a learning rate scheduler update by epoch
            >>> callback = paddle.callbacks.LRScheduler(by_step=False, by_epoch=True)
            >>> model.fit(train_dataset, batch_size=64, callbacks=callback)
    TFby_stepboolby_epochr6   rS   c                H    |r|rt          d          || _        || _        d S )Nz2by_step option is mutually exclusive with by_epoch)
ValueErrorr  r	  )rU   r  r	  s      r$   rV   zLRScheduler.__init__  s:     	x 	D    r#   Nrw   r   rl   rm   c                   | j         r~| j        j        rtt          | j        j        d          r\t	          | j        j        j        t          j        j        j	                  r+| j        j        j        
                                 d S d S d S d S d S N_learning_rate)r	  r,   
_optimizerr   r;   r  r   	optimizerlrrD   r~   r{   s      r$   r}   zLRScheduler.on_epoch_end  s     = 		<
%<DJ13CDD< J)8$'3 < 
%499;;;;;		< 		<< < < < < <r#   r~   c                   | j         r~| j        j        rtt          | j        j        d          r\t	          | j        j        j        t          j        j        j	                  r+| j        j        j        
                                 d S d S d S d S d S r  )r  r,   r  r   r;   r  r   r  r  rD   r~   r   s      r$   r   zLRScheduler.on_train_batch_end  s     < 		<
%<DJ13CDD< J)8$'3 < 
%499;;;;;		< 		<< < < < < <r#   )TF)r  r  r	  r  r6   rS   r:   r   r   )r   r   r    r   rV   r}   r   r"   r#   r$   rD   rD     st        ? ?B! ! ! ! ! 8<< < < < < 7;< < < < < < <r#   rD   c                  H     e Zd ZdZ	 	 	 	 	 	 	 dd fdZdddZdddZ xZS ) rI   a8  Stop training when the given monitor stopped improving during evaluation
    by setting `model.stop_training=True`.

    Args:
        monitor(str): Quantity to be monitored. Default: 'loss'.
        mode(str|None): Mode should be one of 'auto', 'min' or 'max'. In 'min'
            mode, training will stop until monitored quantity stops decreasing.
            In 'max' mode, training will stop until monitored quantity stops
            increasing. In 'auto' mode, exact mode can be inferred by the name
            of monitor. If 'acc' in monitor, the mode will be considered as
            'max', otherwise the mode will be set to 'min'. Default: 'auto'.
        patience(int): Number of epochs with no improvement after which
            training will be stopped. Default: 0.
        verbose(int): The verbosity mode, should be 0 or 1. When verbose=0,
            logs will not be printed. When verbose=1, logs will be printed.
            Default: 1.
        min_delta(int|float): The minimum change of monitored quantity. If
            the change is less than min_delta, model could be considered as no
            improvement. Default: 0.
        baseline(int|float|None): Baseline value for the monitored quantity.
            Training will stop if the model doesn't show improvement over the
            baseline. Default: None.
        save_best_model(bool): Whether to save best model. Default: True.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle import Model
            >>> from paddle.static import InputSpec
            >>> from paddle.vision.models import LeNet
            >>> from paddle.vision.datasets import MNIST
            >>> from paddle.metric import Accuracy
            >>> from paddle.nn import CrossEntropyLoss
            >>> import paddle.vision.transforms as T

            >>> device = paddle.set_device('cpu')
            >>> sample_num = 200
            >>> save_dir = './best_model_checkpoint'
            >>> transform = T.Compose(
            ...     [T.Transpose(), T.Normalize([127.5], [127.5])])
            >>> train_dataset = MNIST(mode='train', transform=transform)
            >>> val_dataset = MNIST(mode='test', transform=transform)
            >>> net = LeNet()
            >>> optim = paddle.optimizer.Adam(
            ...     learning_rate=0.001, parameters=net.parameters())

            >>> inputs = [InputSpec([None, 1, 28, 28], 'float32', 'x')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> model = Model(net, inputs=inputs, labels=labels)
            >>> model.prepare(
            ...     optim,
            ...     loss=CrossEntropyLoss(reduction="sum"),
            ...     metrics=[Accuracy()])
            >>> callbacks = paddle.callbacks.EarlyStopping(
            ...     'loss',
            ...     mode='min',
            ...     patience=1,
            ...     verbose=1,
            ...     min_delta=0,
            ...     baseline=None,
            ...     save_best_model=True)
            >>> model.fit(train_dataset,
            ...           val_dataset,
            ...           batch_size=64,
            ...           log_freq=200,
            ...           save_freq=10,
            ...           save_dir=save_dir,
            ...           epochs=20,
            ...           callbacks=[callbacks])
    r(   autor   r   NTmonitorrd   r4   Literal['auto', 'min', 'max']patiencer   r   	min_deltar'   baselinefloat | Nonesave_best_modelr  r6   rS   c                P   t                                                       || _        || _        || _        || _        t          |          | _        d| _        d | _	        d| _
        || _        d | _        |dvrt          j        d| d           d}|dk    rt          j        | _        nD|dk    rt          j        | _        n,d| j        v rt          j        | _        nt          j        | _        | j        t          j        k    r| xj        d	z  c_        d S | xj        d
z  c_        d S )Nr   r  minmaxzEarlyStopping mode # is unknown, fallback to auto mode.r  r  r  accr   )superrV   r  r  r   r  absr  
wait_epochbest_weightsstopped_epochr  r1   warningswarnnpless
monitor_opgreater)	rU   r  r4   r  r   r  r  r  	__class__s	           r$   rV   zEarlyStopping.__init__x  s!    	  Y .$(---MOdOOO   D5== gDOOU]] jDOO $$"$*"$'?bj((NNaNNNNNNb NNNNr#   rl   rm   c                    d| _         | j        | j        | _        d S | j        t          j        k    rt          j        nt          j         | _        d | _        d S r   )r%  r  
best_valuer,  r*  r+  infr&  r   s     r$   r   zEarlyStopping.on_train_begin  sK    =$"mDOOO(,27(B(BbffDO $Dr#   c           
        |	| j         |vrt          j        d           d S || j                  }t          |t          t
          f          r	|d         }nt          |t          j                  r|}nd S |                     || j	        z
  | j
                  r\|| _
        d| _        | j        rF| j        ?t          j                            | j        d          }| j                            |           n| xj        dz  c_        | j        | j        k    rd| j        _        | j        dk    rt-          d| j        dz    d           | j        ri| j        bt-          d                    t          j                            t          j                            | j        d                                         | xj        dz  c_        d S )	Nz7Monitor of EarlyStopping should be loss or metric name.r   
best_modelr   Tr   z: Early stopping.z$Best checkpoint has been saved at {})r  r(  r)  r;   rF   rG   numbersNumberr,  r  r0  r%  r  r1   r  r  joinr,   r  r  stop_trainingr   r   r'  formatr  )rU   rl   currentr  s       r$   r   zEarlyStopping.on_eval_end  s   <4<t33MI   Ft|$ge}-- 	ajGG00 	GGF??7T^3T_EE 	!%DODO# &(Aw||DM<@@
%%%OOq OO?dm++'+DJ$|aHt1A5HHHIII' DM,E>EEGOO "T]L I I     	ar#   )r(   r  r   r   r   NT)r  rd   r4   r  r  r   r   r   r  r'   r  r  r  r  r6   rS   r:   r   )r   r   r    r   rV   r   r   __classcell__r.  s   @r$   rI   rI   .  s        G GV .4!% $)! )! )! )! )! )! )!V% % % % %"  "  "  "  "  "  "  "  " r#   rI   c                  j    e Zd ZdZddZddZdddZ	 dddZddZ	 dd dZ	dddZ
dddZdddZd	S )!VisualDLa  
    VisualDL callback class. After storing the loss values and evaluation metrics in a log file during the training time , the panel is launched to view the visual results.

    Args:
        log_dir (str): The directory to save visualdl log file.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.vision.transforms as T
            >>> from paddle.static import InputSpec

            >>> inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> transform = T.Compose([
            ...     T.Transpose(),
            ...     T.Normalize([127.5], [127.5])
            ... ])
            >>> train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
            >>> eval_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)

            >>> net = paddle.vision.models.LeNet()
            >>> model = paddle.Model(net, inputs, labels)

            >>> optim = paddle.optimizer.Adam(0.001, parameters=net.parameters())
            >>> model.prepare(optimizer=optim,
            ...             loss=paddle.nn.CrossEntropyLoss(),
            ...             metrics=paddle.metric.Accuracy())

            >>> ## uncomment following lines to fit model with visualdl callback function
            >>> # callback = paddle.callbacks.VisualDL(log_dir='visualdl_log_dir')
            >>> # model.fit(train_dataset, eval_dataset, batch_size=64, callbacks=callback)

    log_dirrd   r6   rS   c                >    || _         d | _        d | _        d| _        d S r   )r>  r   r   rw   )rU   r>  s     r$   rV   zVisualDL.__init__  s"    



r#   r  c                P    t           j                                        j        dk    S r   r   r   r   r   r^   s    r$   	_is_writezVisualDL._is_write      !--//:a??r#   Nrl   rm   c                    | j         d         | _        | j        sJ | j         d         | _        | j        sJ d| _        d| _        d S )Nr   r   Tr   )rO   r   r   _is_fitr   r   s     r$   r   zVisualDL.on_train_begin  sM    k(+{{![3!!!!r#   rw   r.   c                8    | j         d         | _        || _        d S Nr   rO   r   rw   r{   s      r$   ry   zVisualDL.on_epoch_begin       [)



r#   r   r4   r   c                ,   |                                  sd S t          | d          s.t          d          }|                    | j                  | _        t          | | d          }t          | | d          }|dk    r|}n| j        }|D ]}||v r|dz   |z   }t          ||         t          t          f          r||         d         }	n*t          ||         t          j                  r	||         }	ni| j                            |||	           d S )	Nwritervisualdlr   r   r   r   r   )tagr~   value)rB  r   r   	LogWriterr>  rK  rg   rw   r;   rF   rG   r4  r5  
add_scalar)
rU   rl   r4   rL  r   current_step
total_stepr?   temp_tag
temp_values
             r$   r   zVisualDL._updates  s8   ~~ 	FtX&& 	;!*--H",,T\::DK$4 1 1 122t^^^447??%JJJ 	 	ADyy#:>d1ge}55 !%aJJQ88 !%aJJ&& z '   	 	r#   r~   c                    |pi }| xj         dz  c_         |                                 r|                     |d           d S d S Nr   r   r   rB  r   r   s      r$   r   zVisualDL.on_train_batch_end+  S     zr1>> 	)MM$(((((	) 	)r#   c                    |                     dd           | _        |                     dg           | _        d| _        d| _        d S Nr   r   r   r   r   r   r   r   r   s     r$   r   zVisualDL.on_eval_begin4  B    ((7D11 HHY33r#   c                |    t          | d          r+| j                                         t          | d           d S d S )NrK  )r   rK  closedelattrr   s     r$   r   zVisualDL.on_train_end:  sH    4"" 	$KD(#####	$ 	$r#   c                    |                                  ra|                     |d           t          | d          s=t          | d          r/| j                                         t          | d           d S d S d S d S )Nr   rE  rK  )rB  r   r   rK  r^  r_  r   s     r$   r   zVisualDL.on_eval_end?  s    >> 	(MM$'''D),, ('$2I2I (!!###h'''''	( 	(( ( ( (r#   )r>  rd   r6   rS   r6   r  r:   r   r   r   )rl   r   r4   r   r6   rS   r   )r   r   r    r   rV   rB  r   ry   r   r   r   r   r   r"   r#   r$   r=  r=    s       # #J   @ @ @ @     FJ       > 7;) ) ) ) )         $ $ $ $ $
( ( ( ( ( ( (r#   r=  c                      e Zd ZdZ	 	 	 	 	 	 dd dZd Zed             Zd!d"dZ	 d!d#dZ	d$dZ
	 d!d%dZd!d"dZd!d"dZd!d"dZdS )&WandbCallbackaA  Track your training and system metrics using `Weights and Biases <https://docs.wandb.ai>`_.

    **Installation and set-up**

    Install with pip and log in to your W&B account:

    .. code-block:: bash

        pip install wandb
        wandb login

    Args:
        project(str|None, optional): Name of the project. Default: uncategorized
        entity(str|None, optional): Name of the team/user creating the run. Default: Logged in user
        name(str|None, optional): Name of the run. Default: randomly generated by wandb
        dir(str|None, optional): Directory in which all the metadata is stored. Default: `wandb`
        mode(str|None, optional): Can be "online", "offline" or "disabled". Default: "online".
        job_type(str|None, optional): the type of run, for grouping runs together. Default: None

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> import paddle.vision.transforms as T
            >>> from paddle.static import InputSpec

            >>> inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]

            >>> transform = T.Compose([
            ...     T.Transpose(),
            ...     T.Normalize([127.5], [127.5])
            ... ])
            >>> train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
            >>> eval_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)

            >>> net = paddle.vision.models.LeNet()
            >>> model = paddle.Model(net, inputs, labels)

            >>> optim = paddle.optimizer.Adam(0.001, parameters=net.parameters())
            >>> model.prepare(optimizer=optim,
            ...             loss=paddle.nn.CrossEntropyLoss(),
            ...             metrics=paddle.metric.Accuracy())

            >>> ## uncomment following lines to fit model with wandb callback function
            >>> # callback = paddle.callbacks.WandbCallback(project='paddle_mnist')
            >>> # model.fit(train_dataset, eval_dataset, batch_size=64, callbacks=callback)

    Nprojectr2   entityrc   dirr4   /Literal['online', 'offline', 'disabled'] | Nonejob_typekwargsr   r6   rS   c                    t          dd          | _        ||||||d| _        d | _         | j        j        di | | j        }d S )NwandbzVYou want to use `wandb` which is not installed yet install it with `pip install wandb`)rd  rc   re  rf  r4   rh  r"   )r   rk  
wandb_args_runr   run)	rU   rd  re  rc   rf  r4   rh  ri  r   s	            r$   rV   zWandbCallback.__init__{  sl      d
 

  
 
 	(((((Hr#   c                P    t           j                                        j        dk    S r   rA  r^   s    r$   rB  zWandbCallback._is_write  rC  r#   c                    |                                  rU| j        N| j        j        &t	          j        d           | j        j        | _        n | j        j        di | j        | _        | j        S )NzThere is a wandb run already in progress and newly created instances of `WandbCallback` will reuse this run. If this is not desired , call `wandb.finish()` before instantiating `WandbCallback`.r"   )rB  rm  rk  rn  r(  r)  initrl  r^   s    r$   rn  zWandbCallback.run  su    >> 
	Cy :>-MY  
 !%
DII /
 B B$/ B BDIyr#   rl   rm   c                   | j         d         | _        | j        sJ | j         d         | _        | j        sJ d| _        d| _        |                                 rn| j                            d           | j                            dd           | j                            d           | j                            d	d           d S d S )
Nr   r   Tr   
train/stepztrain/*)step_metricrw   zeval/*)rO   r   r   rE  r   rB  rn  define_metricr   s     r$   r   zWandbCallback.on_train_begin  s    k(+{{![3!!!!>> 	BH""<000H""9,"GGGH""7+++H""8"AAAAA	B 	Br#   rw   r   c                8    | j         d         | _        || _        d S rG  rH  r{   s      r$   ry   zWandbCallback.on_epoch_begin  rI  r#   r   c                ^   |                                  sd S t          | | d          }t          | | d          }i }|dk    r|}|                    d|i           n| j        }|                    d|i           |D ]}||v r|dz   |z   }t	          ||         t
          t          f          r$|                    |||         d         i           Tt	          ||         t          j                  r|                    |||         i           | j	        
                    |           d S )Nr   r   r   rs  rw   r   r   )rB  rg   r   rw   r;   rF   rG   r4  r5  rn  log)	rU   rl   r4   r   rQ  r   rR  r?   rS  s	            r$   r   zWandbCallback._updates  sL   ~~ 	F$4 1 1 122t^^^447??%JOO\:67777JOOWj1222 		 		ADyy#:>d1ge}55 OOXtAwqz$:;;;;Q88 OOXtAw$78888  	Xr#   r~   c                    |pi }| xj         dz  c_         |                                 r|                     |d           d S d S rV  rW  r   s      r$   r   z WandbCallback.on_train_batch_end  rX  r#   c                    |                     dd           | _        |                     dg           | _        d| _        d| _        d S rZ  r[  r   s     r$   r   zWandbCallback.on_eval_begin  r\  r#   c                d    |                                  r| j                                         d S d S r:   )rB  rn  finishr   s     r$   r   zWandbCallback.on_train_end  s6    >> 	HOO	 	r#   c                    |                                  ra|                     |d           t          | d          s=t          | d          r/| j                                         t          | d           d S d S d S d S )Nr   rE  rn  )rB  r   r   rn  r|  r_  r   s     r$   r   zWandbCallback.on_eval_end  s    >> 	%MM$'''D),, %'$2F2F %!!!e$$$$$	% 	%% % % %r#   )NNNNNN)rd  r2   re  r2   rc   r2   rf  r2   r4   rg  rh  r2   ri  r   r6   rS   r:   r   r   r   r   )r   r   r    r   rV   rB  propertyrn  r   ry   r   r   r   r   r   r"   r#   r$   rc  rc  H  s2       0 0h #!@D#    :@ @ @   XB B B B B  8<       < 7;) ) ) ) )             % % % % % % %r#   rc  c                       e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   ded<   ded<   ded<   	 	 	 	 	 	 	 	 d d! fdZd"dZd#d$dZd#d$dZd%dZ	 xZ
S )&ReduceLROnPlateaua  Reduce learning rate when a metric of evaluation has stopped improving.
    Models often benefit from reducing the learning rate by a factor
    of 2-10 once learning stagnates. This callback monitors a
    quantity and if no improvement is seen for a 'patience' number
    of epochs, the learning rate is reduced.

    Args:
        monitor(str, optional): Quantity to be monitored. Default: 'loss'.
        factor(float, optional): factor by which the learning rate will be reduced.
            `new_lr = lr * factor`. Default: 0.1.
        patience(int, optional): Number of epochs with no improvement after which
            learning rate will be reduced. Default: 10.
        verbose(int, optional): The verbosity mode. 0: quiet, 1: update messages.
            Default: 1.
        mode(str, optional): one of `{'auto', 'min', 'max'}`. In `'min'` mode,
            the learning rate will be reduced when the quantity monitored has
            stopped decreasing. In 'max' mode, learning rate will reduce until
            monitored quantity stops increasing. In 'auto' mode, exact mode
            can be inferred by the name of monitor. If 'acc' in monitor, the
            mode will be considered as 'max', otherwise the mode will be set
            to 'min'. Default: 'auto'.
        min_delta(int|float, optional): threshold for measuring the new optimum,
            to only focus on significant changes. Default: 0.
        cooldown(int, optional): number of epochs to wait before resuming normal operation after
            lr has been reduced. Default: 0.
        min_lr(float, optional): lower bound on the learning rate. Default: 0.

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> from paddle import Model
            >>> from paddle.static import InputSpec
            >>> from paddle.vision.models import LeNet
            >>> from paddle.vision.datasets import MNIST
            >>> from paddle.metric import Accuracy
            >>> from paddle.nn.layer.loss import CrossEntropyLoss
            >>> import paddle.vision.transforms as T
            >>> sample_num = 200
            >>> transform = T.Compose(
            ...      [T.Transpose(), T.Normalize([127.5], [127.5])])
            >>> train_dataset = MNIST(mode='train', transform=transform)
            >>> val_dataset = MNIST(mode='test', transform=transform)
            >>> net = LeNet()
            >>> optim = paddle.optimizer.Adam(
            ...     learning_rate=0.001, parameters=net.parameters())
            >>> inputs = [InputSpec([None, 1, 28, 28], 'float32', 'x')]
            >>> labels = [InputSpec([None, 1], 'int64', 'label')]
            >>> model = Model(net, inputs=inputs, labels=labels)
            >>> model.prepare(
            ...     optim,
            ...     loss=CrossEntropyLoss(),
            ...     metrics=[Accuracy()])
            >>> callbacks = paddle.callbacks.ReduceLROnPlateau(patience=3, verbose=1)
            >>> model.fit(train_dataset,
            ...             val_dataset,
            ...             batch_size=64,
            ...             log_freq=200,
            ...             save_freq=10,
            ...             epochs=20,
            ...             callbacks=[callbacks])

    rd   r  r'   factorr   r  r   r  r4   r  cooldownmin_lrr(   皙?
   r   r  -C6?r   r6   rS   c	                P   t                                                       || _        |dk    rt          d          || _        || _        || _        || _        || _        || _	        d| _
        d| _        d| _        || _        d | _        d| _        |                                  d S )Nr   z3ReduceLROnPlateau does not support a factor >= 1.0.r   )r#  rV   r  r  r  r  r  r  r   r  cooldown_counterwaitbestr4   r,  rw   _reset)
rU   r  r  r  r   r4   r  r  r  r.  s
            r$   rV   zReduceLROnPlateau.__init__C  s     	S==E   "   !			
r#   c                ,     j         dvr$t          j        d j          d           d _          j         dk    s j         dk    r%d j        vr fd _        t
          j         _        n fd _        t
          j          _        d	 _        d	 _	        d
S )z)Resets wait counter and cooldown counter.r  zLearning rate reduction mode r   r  r  r!  c                >    t          j        | |j        z
            S r:   )r*  r+  r  abrU   s     r$   <lambda>z*ReduceLROnPlateau._reset.<locals>.<lambda>o  s    271a$.6H+I+I r#   c                >    t          j        | |j        z             S r:   )r*  r-  r  r  s     r$   r  z*ReduceLROnPlateau._reset.<locals>.<lambda>r  s    2:aT^9K+L+L r#   r   N)
r4   r(  r)  r  r,  r*  r1  r  r  r  r^   s   `r$   r  zReduceLROnPlateau._resetd  s    9222M)	 ) ) )   DI9IE$=$=IIIIDODIILLLLDODI !			r#   Nrl   rm   c                .    |                                   d S r:   )r  r   s     r$   r   z ReduceLROnPlateau.on_train_beginw  s    r#   c                   |	| j         |vrt          j        d           d S 	 | j        j        j        }t          |t                    s't          j        dt          |           d           d S n0# t          $ r#}t          j        d| d           Y d }~d S d }~ww xY w|| j                  }t          |t          t          f          r	|d         }nt          |t          j                  r|}nd S |                                 r| xj        dz  c_        d| _        |                     || j                  r|| _        d| _        n|                                 s| xj        dz  c_        | j        | j        k    r| j        j                                        }|t+          j        | j                  k    r|| j        z  }t3          || j                  }|| j        j        _        | j        dk    rEt6          j                                        j        dk    rt?          d| j         dz    d| d           | j!        | _        d| _        | xj         dz  c_         d S )	Nz;Monitor of ReduceLROnPlateau should be loss or metric name.z)Expected learning_rate be float, bug got .zAThere are something wrong when get learning_rate from optimizer: r   r   z
Epoch z.: ReduceLROnPlateau reducing learning rate to )"r  r(  r)  r,   r  r  r;   r'   type	ExceptionrF   rG   r4  r5  in_cooldownr  r  r,  r  r  get_lrr*  float32r  r  r  r   r   r   r   r   r   rw   r  )rU   rl   r  er9  old_lrnew_lrs          r$   r   zReduceLROnPlateau.on_eval_endz  s   <4<t33MM   FZ*9!"e,, MODHHOOO   F	
    \XY\\\   	 t|$ge}-- 	ajGG00 	GGF 	!!Q&!!DI??7DI.. 	"DIDII!!## 	"IINIIyDM)).5577BJt{3333#dk1F 55F;ADJ)8q((".::<<G1LL1tzA~ 1 1'-1 1 1   -1MD) !DI

a



s   AA1 1
B;BBr  c                    | j         dk    S r   )r  r^   s    r$   r  zReduceLROnPlateau.in_cooldown  s    $q((r#   )r(   r  r  r   r  r  r   r   )r  rd   r  r'   r  r   r   r   r4   r  r  r'   r  r   r  r'   r6   rS   r   r:   r   ra  )r   r   r    r   r!   rV   r  r   r   r  r:  r;  s   @r$   r  r    s        > >@ LLLMMMMMMLLL''''MMMMMM .4      B   &    5 5 5 5 5n) ) ) ) ) ) ) )r#   r  )NNNNNr)   r)   r   NNr   )r*   r+   r,   r-   r   r.   r   r.   r   r.   r/   r   r   r   r0   r   r1   r2   r   r3   r4   r5   r6   r7   )(
__future__r   r4  r  r   r(  typingr   numpyr*  r   paddle.utilsr   progressbarr   r   r	   r
   collection.abcr   r   typing_extensionsr   r,   r   r   r!   r   r&   __all__rP   r7   rX   r<   rB   rD   rI   r=  rc  r  r"   r#   r$   <module>r     sn   # " " " " " "  				                    # # # # # # $ $ $ $ $ $ ..........11111111++++++&'ABMBBBB    )       	     7;! $%,( ( ( ( (VL% L% L% L% L% L% L% L%^y y y y y y y yxM= M= M= M= M=H M= M= M=`F" F" F" F" F"h F" F" F"Re< e< e< e< e<( e< e< e<P_  _  _  _  _ H _  _  _ Du( u( u( u( u(x u( u( u(pn% n% n% n% n%H n% n% n%by) y) y) y) y) y) y) y) y) y)r#   