a
    d-                     @   sz   d dl mZmZmZmZ d dlZd dlmZ d dl	m
Z
 d dlmZ G dd deZdd	eeeeef f d
ddZdS )    )AnyDictOptionalUnionN)Callback)_version)rank_zero_warnc                   @   s  e Zd ZdZddddZeddddZeedd	d
ZeedddZ	eedddZ
eedddZeedddZeedddZeedddZeedddZeedddZeedddZeeeef dddZeeeef ddd Zeeeef dd!d"Zeeeef dd#d$Zeeeef dd%d&Zeeeef dd'd(Zeed)d*d+Zddd,d-Zddd.d/Zddd0d1Ze e dd2d3d4Z!dd5edd6d7d8Z"dd5e#eeeeee#eef f f d9d:d;Z$dS )<ProgressBarBasea  
    The base class for progress bars in Lightning. It is a :class:`~pytorch_lightning.callbacks.Callback`
    that keeps track of the batch progress in the :class:`~pytorch_lightning.trainer.trainer.Trainer`.
    You should implement your highly custom progress bars with this as the base class.

    Example::

        class LitProgressBar(ProgressBarBase):

            def __init__(self):
                super().__init__()  # don't forget this :)
                self.enable = True

            def disable(self):
                self.enable = False

            def on_train_batch_end(self, trainer, pl_module, outputs, batch_idx):
                super().on_train_batch_end(trainer, pl_module, outputs, batch_idx)  # don't forget this :)
                percent = (self.train_batch_idx / self.total_train_batches) * 100
                sys.stdout.flush()
                sys.stdout.write(f'{percent:.01f} percent complete \r')

        bar = LitProgressBar()
        trainer = Trainer(callbacks=[bar])

    N)returnc                 C   s   d | _ d | _d S N)_trainer_current_eval_dataloader_idxself r   r/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/callbacks/progress/base.py__init__2   s    zProgressBarBase.__init__
pl.Trainerc                 C   s$   | j d u rtd| jj d| j S )NzThe `z*._trainer` reference has not been set yet.)r   	TypeError	__class____name__r   r   r   r   trainer6   s    
zProgressBarBase.trainerc                 C   s   dS )NzSanity Checkingr   r   r   r   r   sanity_check_description<   s    z(ProgressBarBase.sanity_check_descriptionc                 C   s   dS )NZTrainingr   r   r   r   r   train_description@   s    z!ProgressBarBase.train_descriptionc                 C   s   dS )NZ
Validationr   r   r   r   r   validation_descriptionD   s    z&ProgressBarBase.validation_descriptionc                 C   s   dS )NZTestingr   r   r   r   r   test_descriptionH   s    z ProgressBarBase.test_descriptionc                 C   s   dS )NZ
Predictingr   r   r   r   r   predict_descriptionL   s    z#ProgressBarBase.predict_descriptionc                 C   s   | j jjjjjjjS r   )r   fit_loop
epoch_loopval_loopbatch_progresstotal	processedr   r   r   r   _val_processedP   s    zProgressBarBase._val_processedc                 C   s   | j jjjjjS )zhThe number of batches processed during training.

        Use this to update your progress bar.
        )r   r   r   r    currentr"   r   r   r   r   train_batch_idxU   s    zProgressBarBase.train_batch_idxc                 C   s4   | j jjdkr| j jjj}n| j j}|jjjj	}|S )zjThe number of batches processed during validation.

        Use this to update your progress bar.
        Zfit)
r   statefnr   r   r   Zvalidate_loopr    r$   r"   )r   ZloopZcurrent_batch_idxr   r   r   val_batch_idx]   s
    zProgressBarBase.val_batch_idxc                 C   s   | j jjjjjS )zgThe number of batches processed during testing.

        Use this to update your progress bar.
        )r   Z	test_loopr   r    r$   r"   r   r   r   r   test_batch_idxk   s    zProgressBarBase.test_batch_idxc                 C   s   | j jjjjjS )zjThe number of batches processed during prediction.

        Use this to update your progress bar.
        )r   Zpredict_loopr   r    r$   r"   r   r   r   r   predict_batch_idxs   s    z!ProgressBarBase.predict_batch_idxc                 C   s   | j jS )zThe total number of training batches, which may change from epoch to epoch.

        Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the training
        dataloader is of infinite size.
        )r   Znum_training_batchesr   r   r   r   total_train_batches{   s    z#ProgressBarBase.total_train_batchesc                 C   s2   | j dusJ | jjr$| jj| j  S | jj| j  S )a  The total number of validation batches, which may change from epoch to epoch for current dataloader.

        Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the validation
        dataloader is of infinite size.
        N)r   r   Zsanity_checkingZnum_sanity_val_batchesnum_val_batchesr   r   r   r   $total_val_batches_current_dataloader   s    z4ProgressBarBase.total_val_batches_current_dataloaderc                 C   s   | j dusJ | jj| j  S )zThe total number of testing batches, which may change from epoch to epoch for current dataloader.

        Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the test dataloader is
        of infinite size.
        N)r   r   Znum_test_batchesr   r   r   r   %total_test_batches_current_dataloader   s    z5ProgressBarBase.total_test_batches_current_dataloaderc                 C   s   | j dusJ | jj| j  S )a  The total number of prediction batches, which may change from epoch to epoch for current dataloader.

        Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader
        is of infinite size.
        N)r   r   Znum_predict_batchesr   r   r   r   (total_predict_batches_current_dataloader   s    z8ProgressBarBase.total_predict_batches_current_dataloaderc                 C   s   | j jj rt| j jS dS )a  The total number of validation batches, which may change from epoch to epoch for all val dataloaders.

        Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader
        is of infinite size.
        r   )r   r   r   Z_should_check_val_epochsumr,   r   r   r   r   total_val_batches   s    z!ProgressBarBase.total_val_batchesc                 C   s   | j }| j}| jd usJ |tdkrz|tdkrz| jj}| jjd u rj| jjjd }|| | ||  }n|| }|| }|| S )Ninf   )	r+   r1   r   floatr   val_check_batchZcheck_val_every_n_epochr   Ztotal_batch_idx)r   r+   r1   r5   Ztrain_batches_processedZval_checks_per_epochr   r   r   total_batches_current_epoch   s    
z+ProgressBarBase.total_batches_current_epoch)dataloader_idxr
   c                 C   s   | j }|| _ ||kS r   r   )r   r7   Zold_dataloader_idxr   r   r   has_dataloader_changed   s    z&ProgressBarBase.has_dataloader_changedc                 C   s
   d | _ d S r   r8   r   r   r   r   reset_dataloader_idx_tracker   s    z,ProgressBarBase.reset_dataloader_idx_trackerc                 C   s   t dS )z5You should provide a way to disable the progress bar.NNotImplementedErrorr   r   r   r   disable   s    zProgressBarBase.disablec                 C   s   t dS )aJ  You should provide a way to enable the progress bar.

        The :class:`~pytorch_lightning.trainer.trainer.Trainer` will call this in e.g. pre-training
        routines like the :ref:`learning rate finder <advanced/training_tricks:Learning Rate Finder>`.
        to temporarily enable and disable the main progress bar.
        Nr;   r   r   r   r   enable   s    zProgressBarBase.enable)argskwargsr
   c                 O   s   t |i | dS )zDYou should provide a way to print without breaking the progress bar.N)print)r   r?   r@   r   r   r   rA      s    zProgressBarBase.printpl.LightningModule)r   	pl_modulestager
   c                 C   s   || _ |js|   d S r   )r   Zis_global_zeror=   )r   r   rC   rD   r   r   r   setup   s    zProgressBarBase.setupr   rC   r
   c                 C   sT   t ||}|j}t| | @ }|rHtdd| d|d  d i ||S )af  
        Combines progress bar metrics collected from the trainer with standard metrics from get_standard_metrics.
        Implement this to override the items displayed in the progress bar.

        Here is an example of how to override the defaults:

        .. code-block:: python

            def get_metrics(self, trainer, model):
                # don't show the version number
                items = super().get_metrics(trainer, model)
                items.pop("v_num", None)
                return items

        Return:
            Dictionary with the items to be displayed in the progress bar.
        z;The progress bar already tracks a metric with the name(s) 'z, z' and `self.log('r   z', ..., prog_bar=True)` will overwrite this value.  If this is undesired, change the name or override `get_metrics()` in the progress bar callback.)get_standard_metricsZprogress_bar_metricslistkeysr   join)r   r   rC   Zstandard_metricsZpbar_metrics
duplicatesr   r   r   get_metrics   s    
zProgressBarBase.get_metrics)%r   
__module____qualname____doc__r   propertyr   strr   r   r   r   r   intr#   r%   r(   r)   r*   r   r4   r+   r-   r.   r/   r1   r6   boolr9   r:   r=   r>   r   rA   rE   r   rL   r   r   r   r   r	      sZ   			r	   r   rB   rF   c                 C   s   | j j }d}|dur&|  }n|jr4td}i }|durL|d|d< |jdkrb| j j|d< | j	rt
| j	}|durt|tr|dd }||d< |S )	u  
    Returns several standard metrics displayed in the progress bar, including the average loss value,
    split index of BPTT (if used) and the version of the experiment when using a logger.

    .. code-block::

        Epoch 1:   4%|▎         | 40/1095 [00:03<01:37, 10.84it/s, loss=4.501, v_num=10]

    Return:
        Dictionary with the standard metrics to be displayed in the progress bar.
    NNaNz.3gZlossr   	split_idxZv_num)r   Zrunning_lossmeancpuitemZautomatic_optimizationr4   Ztruncated_bptt_stepsrU   loggersr   
isinstancerQ   )r   rC   Zrunning_train_lossZavg_training_lossZ
items_dictversionr   r   r   rG     s$    


rG   )typingr   r   r   r   Zpytorch_lightningplZpytorch_lightning.callbacksr   Z"pytorch_lightning.utilities.loggerr   Z%pytorch_lightning.utilities.rank_zeror   r	   rQ   rR   rG   r   r   r   r   <module>   s    m