a
    d09                     @   s   d dl mZmZmZmZ d dl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 d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZ G dd deZG dd dZddeeedf  ee ee ed ddddZdS )    )AnyDictOptionalUnion)LiteralNotRequired	TypedDictN)BatchSizeFinder)Callback)LearningRateFinder)LightningDataModule)TrainerStatus)	_LRFinder)MisconfigurationException)EVAL_DATALOADERSTRAIN_DATALOADERSc                   @   s.   e Zd ZU eee  ed< eee  ed< dS )_TunerResultlr_findscale_batch_sizeN)__name__
__module____qualname__r   r   r   __annotations__int r   r   g/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/tuner/tuning.pyr      s   
r   c                   @   s6  e Zd ZdZdddddZeeef eeef dddd	Zd%de	ee
ef  e	e e	e e	e e	eeef  e	eeef  ed ed	ddZeeddddZd&de	ee
df  e	e e	e e	d ed eeeeee	e dddZd'de	ee
df  e	e e	e e	d ed eeeeeee	e d"d#d$ZdS )(TunerzTuner class to tune your model.
pl.TrainerN)trainerreturnc                 C   s
   || _ d S N)r   )selfr   r   r   r   __init__%   s    zTuner.__init__)auto_lr_findauto_scale_batch_sizer   c                 C   s   || j _|| j _d S r    )r   r#   r$   )r!   r#   r$   r   r   r   on_trainer_init(   s    zTuner.on_trainer_initfitzpl.LightningModuler&   validatetestpredict)	modeltrain_dataloadersval_dataloadersdataloaders
datamodulescale_batch_size_kwargslr_find_kwargsmethodr   c	                 C   s0  |pi }|pi }t  }	| jj| | jj}
| jjjrP|
rPtd| jjjd| jjrt	| jjt
rv|d| jj | j||||||fi ||	d< | jjr,tj| jj_t	|tr|}d }|d us|d ur|d urtd| jjj||||d |dd | j||||||fi ||	d	< tj| jj_|	S )
NzC`trainer.tune()` is currently not supported with `Trainer(strategy=z)`.moder   zlYou cannot pass `train_dataloader` or `val_dataloaders` to `trainer.tune()` if datamodule is already passed.)r,   r-   r/   update_attrTr   )r   r   Zstrategyconnectr$   Z_accelerator_connectorZis_distributedr   Zstrategy_name
isinstancestr
setdefaultr   r#   r   RUNNINGstatestatusr   Z_data_connectorZattach_datar   FINISHED)r!   r+   r,   r-   r.   r/   r0   r1   r2   resultZ	is_tuningr   r   r   _tune,   sN    



zTuner._tune)argskwargsr   c                 O   s*   t j| jj_d| j_| jj|i | dS )z[`_run` wrapper to set the proper state during tuning, as this can be called multiple times.TN)r   r9   r   r:   r;   Ztraining_run)r!   r?   r@   r   r   r   rA   l   s    z
Tuner._runpower         
batch_sizepl.LightningDataModule)r+   r,   r-   r.   r/   r2   r3   steps_per_trialinit_val
max_trialsbatch_arg_namer   c                    s   t | j|||| t|||	|
|d d _ g| jj | j_|dkrX| j|||| nR|dkrt| jj|||d n6|dkr| jj|||d n|dkr| jj|||d  fdd	| jjD | j_d
| j_	 j
S )a  Iteratively try to find the largest batch size for a given model that does not give an out of memory
        (OOM) error.

        Args:
            model: Model to tune.

            train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a
                :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples.
                In the case of multiple dataloaders, please see this :ref:`section <multiple-dataloaders>`.

            val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples.

            dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying val/test/predict
                samples used for running tuner on validation/testing/prediction.

            datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.

            method: Method to run tuner on. It can be any of ``("fit", "validate", "test", "predict")``.

            mode: Search strategy to update the batch size:

                - ``'power'``: Keep multiplying the batch size by 2, until we get an OOM error.
                - ``'binsearch'``: Initially keep multiplying by 2 and after encountering an OOM error
                    do a binary search between the last successful batch size and the batch size that failed.

            steps_per_trial: number of steps to run with a given batch size.
                Ideally 1 should be enough to test if an OOM error occurs,
                however in practise a few are needed

            init_val: initial batch size to start the search with

            max_trials: max number of increases in batch size done before
               algorithm is terminated

            batch_arg_name: name of the attribute that stores the batch size.
                It is expected that the user has provided a model or datamodule that has a hyperparameter
                with that name. We will look for this attribute name in the following places

                - ``model``
                - ``model.hparams``
                - ``trainer.datamodule`` (the datamodule passed to the tune method)
        )r3   rH   rI   rJ   rK   Tr&   r(   )r/   r)   r*   c                    s   g | ]}| ur|qS r   r   .0cbZbatch_size_finderr   r   
<listcomp>       z*Tuner.scale_batch_size.<locals>.<listcomp>F)_check_tuner_configurationr   r	   _early_exit	callbacksr&   r(   r)   r*   r$   Zoptimal_batch_size)r!   r+   r,   r-   r.   r/   r2   r3   rH   rI   rJ   rK   r   rO   r   r   r   s*    8zTuner.scale_batch_size:0yE>   d   exponential      @F)r+   r,   r-   r.   r/   r2   min_lrmax_lrnum_trainingr3   early_stop_thresholdr4   r   c                    s   |dkrt dt| j|||| t|||	|
||d d _ g| jj | j_| j||||  fdd| jjD | j_d| j_ jS )aY  Enables the user to do a range test of good initial learning rates, to reduce the amount of guesswork in
        picking a good starting learning rate.

        Args:
            model: Model to tune.

            train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a
                :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples.
                In the case of multiple dataloaders, please see this :ref:`section <multiple-dataloaders>`.

            val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples.

            dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying val/test/predict
                samples used for running tuner on validation/testing/prediction.

            datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.

            min_lr: minimum learning rate to investigate

            max_lr: maximum learning rate to investigate

            num_training: number of learning rates to test

            mode: Search strategy to update learning rate after each batch:

                - ``'exponential'``: Increases the learning rate exponentially.
                - ``'linear'``: Increases the learning rate linearly.

            early_stop_threshold: Threshold for stopping the search. If the
                loss at any point is larger than early_stop_threshold*best_loss
                then the search is stopped. To disable, set to None.

            update_attr: Whether to update the learning rate attribute or not.

        Raises:
            MisconfigurationException:
                If learning rate/lr in ``model`` or ``model.hparams`` isn't overridden when ``auto_lr_find=True``,
                or if you are using more than one optimizer.
        r&   z:method='fit' is an invalid configuration to run lr finder.)rZ   r[   Znum_training_stepsr3   r]   r4   Tc                    s   g | ]}| ur|qS r   r   rL   Zlr_finder_callbackr   r   rP     rQ   z!Tuner.lr_find.<locals>.<listcomp>F)	r   rR   r   r   rS   rT   r&   r#   Z
optimal_lr)r!   r+   r,   r-   r.   r/   r2   rZ   r[   r\   r3   r]   r4   r   r^   r   r      s"    6	zTuner.lr_find)NNNNNNr&   )
NNNNr&   rB   rC   rD   rE   rF   )NNNNr&   rU   rV   rW   rX   rY   F)r   r   r   __doc__r"   r   r7   boolr%   r   r   r   r   r   r   r   r   r>   rA   r   r   floatr   r   r   r   r   r   r   "   s   "       @	          U           r   r&   r   rG   r'   )r   r,   r-   r.   r2   r   c                 C   s   d}||vr"t d|d| d|dkrD|d urdtd|dn |d usT|d urdtd|d	g }| jD ]:}t|tr| jr|d
 qnt|trn| jrn|d qnt	|dkrtd|d  dnt	|dkrtdd S )Nr'   zmethod z is invalid. Should be one of .r&   zIn tuner with method=zs, `dataloaders` argument should be None, please consider setting `train_dataloaders` and `val_dataloaders` instead.zIn tuner with `method`=zt, `train_dataloaders` and `val_dataloaders` arguments should be None, please consider setting `dataloaders` instead.r	   r   rV   z&Trainer is already configured with a `r   z9` callback.Please remove it if you want to use the Tuner.rD   zTrainer is already configured with `LearningRateFinder` and `BatchSizeFinder` callbacks. Please remove them if you want to use the Tuner.)

ValueErrorr   rT   r6   r	   r$   appendr   r#   len)r   r,   r-   r.   r2   Zsupported_methodsZconfigured_callbacksrN   r   r   r   rR     s4    


rR   )NNNr&   )typingr   r   r   r   Ztyping_extensionsr   r   r   Zpytorch_lightningplZ-pytorch_lightning.callbacks.batch_size_finderr	   Z$pytorch_lightning.callbacks.callbackr
   Z%pytorch_lightning.callbacks.lr_finderr   Z!pytorch_lightning.core.datamoduler   Z pytorch_lightning.trainer.statesr   Z!pytorch_lightning.tuner.lr_finderr   Z&pytorch_lightning.utilities.exceptionsr   Z!pytorch_lightning.utilities.typesr   r   r   r   rR   r   r   r   r   <module>   s2    t    