o
    zi,                     @   s   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mZ er,d dlmZ G dd dZ					dd
eeedf  dee dee ded ddf
ddZdddZdddZdS )    )TYPE_CHECKINGLiteralOptionalUnionN)Callback)MisconfigurationException)EVAL_DATALOADERSTRAIN_DATALOADERS)	_LRFinderc                   @   s
  e Zd ZdZd.ddZ								
			d/dddeeedf  dee dee ded de	d de
dededede
dee fddZ								 	!	"	#	$d0dddeeedf  dee dee ded de	d d%ed&ed'ede
d(ee d)ed*e
ded+ fd,d-ZdS )1TunerzTuner class to tune your model.trainer
pl.TrainerreturnNc                 C   s
   || _ d S )N)_trainer)selfr    r   R/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_lightning/tuner/tuning.py__init__   s   
zTuner.__init__fitpower         
batch_sizemodelzpl.LightningModuletrain_dataloaderspl.LightningDataModuleval_dataloadersdataloaders
datamodulemethodr   validatetestpredictmodesteps_per_trialinit_val
max_trialsbatch_arg_namec                    s   t |||| t| j ddlm} ||||	|
|d d _ g| jj | j_|dkr5| j|||| n)|dkrC| jj|||d n|dkrQ| jj	|||d n|d	kr^| jj
|||d  fd
d| j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)

        r   BatchSizeFinder)r%   r&   r'   r(   r)   Tr   r"   )r   r#   r$   c                       g | ]}| ur|qS r   r   .0cbbatch_size_finderr   r   
<listcomp>i       z*Tuner.scale_batch_size.<locals>.<listcomp>)_check_tuner_configuration%_check_scale_batch_size_configurationr   -pytorch_lightning.callbacks.batch_size_finderr+   _early_exit	callbacksr   r"   r#   r$   optimal_batch_size)r   r   r   r   r   r   r    r%   r&   r'   r(   r)   r+   r   r0   r   scale_batch_size   s,   0
zTuner.scale_batch_size:0yE>   d   exponential      @T min_lrmax_lrnum_trainingearly_stop_thresholdupdate_attr	attr_namer
   c              	      s   |dkrt dt|||| t| j ddlm} ||||	|
|||d d _ g| jj | j_| j||||  fdd| jjD | j_ j	S )	aX  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`.
            method: Method to run tuner on. It can be any of ``("fit", "validate", "test", "predict")``.
            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.
            attr_name: Name of the attribute which stores the learning rate. The names 'learning_rate' or 'lr' get
                automatically detected. Otherwise, set the name here.

        Raises:
            MisconfigurationException:
                If learning rate/lr in ``model`` or ``model.hparams`` isn't overridden,
                or if you are using more than one optimizer.

        r   z>method='fit' is the only valid configuration to run lr finder.r   LearningRateFinder)rA   rB   num_training_stepsr%   rD   rE   rF   Tc                    r,   r   r   r-   lr_finder_callbackr   r   r2      r3   z!Tuner.lr_find.<locals>.<listcomp>)
r   r4   _check_lr_find_configurationr   %pytorch_lightning.callbacks.lr_finderrH   r7   r8   r   
optimal_lr)r   r   r   r   r   r   r    rA   rB   rC   r%   rD   rE   rF   rH   r   rJ   r   lr_findl   s&   2

zTuner.lr_findr   r   r   N)
NNNNr   r   r   r   r   r   )NNNNr   r;   r<   r=   r>   r?   Tr@   )__name__
__module____qualname____doc__r   r   r   r	   r   r   strintr:   floatboolrO   r   r   r   r   r      s    
	

P	
r   r   r   r   r   r   r    r!   r   c                 C   sj   d}||vrt d|d| d|dkr#|d ur!td|dd S | d us+|d ur3td|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.)
ValueErrorr   )r   r   r   r    supported_methodsr   r   r   r4      s   

r4   r   r   c                    s0   ddl m   fdd| jD }|rtdd S )Nr   rG   c                       g | ]	}t | r|qS r   
isinstancer-   rG   r   r   r2          z0_check_lr_find_configuration.<locals>.<listcomp>zqTrainer is already configured with a `LearningRateFinder` callback.Please remove it if you want to use the Tuner.)rM   rH   r8   rZ   r   configured_callbacksr   rG   r   rL      s   rL   c                    s@   | j jrtdddlm   fdd| jD }|rtdd S )NzMTuning the batch size is currently not supported with distributed strategies.r   r*   c                    r\   r   r]   r-   r*   r   r   r2      r_   z9_check_scale_batch_size_configuration.<locals>.<listcomp>znTrainer is already configured with a `BatchSizeFinder` callback.Please remove it if you want to use the Tuner.)_accelerator_connectoris_distributedrZ   r6   r+   r8   r`   r   r*   r   r5      s   r5   )NNNr   rP   )typingr   r   r   r   pytorch_lightningpl$pytorch_lightning.callbacks.callbackr   &pytorch_lightning.utilities.exceptionsr   !pytorch_lightning.utilities.typesr   r	   !pytorch_lightning.tuner.lr_finderr
   r   r4   rL   r5   r   r   r   r   <module>   s4    $

