
      iq/                         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      Z	 	 	 	 dd	eeed
f      dee   dee   ded   ddf
dZddZddZy)    )TYPE_CHECKINGLiteralOptionalUnionN)Callback)MisconfigurationException)EVAL_DATALOADERSTRAIN_DATALOADERS)	_LRFinderc                   .   e Zd ZdZ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dedee   f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e   dede
ded   fdZy)!TunerzTuner class to tune your model.returnNc                     || _         y )N)_trainer)selftrainers     s/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/pytorch_lightning/tuner/tuning.py__init__zTuner.__init__   s	        modelzpl.LightningModuletrain_dataloaderspl.LightningDataModuleval_dataloadersdataloaders
datamodulemethodfitvalidatetestpredictmodesteps_per_trialinit_val
max_trialsbatch_arg_namemarginmax_valc           	         t        ||||       t        | j                         d|cxk  rdk  sn J d|       ddlm}  ||||	|
|||      }d|_        |g| j                  j                  z   | j                  _        |dk(  r| j                  j                  ||||       nk|d	k(  r| j                  j                  |||
       nG|dk(  r| j                  j                  |||
       n#|dk(  r| j                  j                  |||
       | j                  j                  D cg c]	  }||us| c}| j                  _        |j                  S c c}w )ad
  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)

            margin: Margin to reduce the found batch size by to provide a safety buffer. Only applied when using
                'binsearch' mode. Should be a float between 0 and 1. Defaults to 0.05 (5% reduction).
            max_val: Maximum batch size limit, defaults to 8192.
                Helps prevent testing unrealistically large or inefficient batch sizes (e.g., 2**25)
                when running on CPU or when automatic OOM detection is not available.

        g        g      ?z1`margin` should be between 0 and 1. Found margin=r   BatchSizeFinder)r"   r#   r$   r%   r&   r'   r(   Tr   r   )r   r    r!   )_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(   r+   batch_size_findercbs                    r   scale_batch_sizezTuner.scale_batch_size   sV   p 	##4o{TZ[-dmm<f"s"Z&XQWPY$ZZ" 	R&5+!)'
 )-%#4"58O8O"OU?MMe%6Tz!MM""5+*"MvMMukjIy MM!!%!L040G0G"g0G"2UfKf20G"g 333 #hs   '	E1Emin_lrmax_lrnum_trainingearly_stop_thresholdupdate_attr	attr_namer   c           	         |dk7  rt        d      t        ||||       t        | j                         ddlm}  ||||	|
|||      }d|_        |g| j                  j                  z   | j                  _        | j                  j                  ||||       | j                  j                  D cg c]	  }||us| c}| j                  _        |j                  S c c}w )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)r5   r6   num_training_stepsr"   r8   r9   r:   T)
r   r,   _check_lr_find_configurationr   %pytorch_lightning.callbacks.lr_finderr=   r/   r0   r   
optimal_lr)r   r   r   r   r   r   r   r5   r6   r7   r"   r8   r9   r:   r=   lr_finder_callbackr3   s                    r   lr_findzTuner.lr_findw   s    d U?+,lmm"#4o{TZ[$T]]3 	M'9+!5#(
 *.&#5"69P9P"P%!2OZP040G0G"h0G"2UgKg20G"h!,,, #is   /	C9Cr   z
pl.Trainerr   N)NNNNr   power         
batch_sizeg?i    )NNNNr   g:0yE>   d   exponentialg      @T )__name__
__module____qualname____doc__r   r   r   r
   r	   r   strintfloatr4   boolrC    r   r   r   r      s   )  [_6:269=@E *V4#V4 $E*;=U*U$VWV4 ""23	V4
 ./V4 56V4 <=V4 V4 V4 V4 V4 V4 V4 V4 
#V4v [_6:269=@E!03 L-#L- $E*;=U*U$VWL- ""23	L-
 ./L- 56L- <=L- L- L- L- L- 'uoL- L- L- 
+	L-r   r   r   r   r   r   r   r   r   c                     d}||vrt        d|d| d      |dk(  r|t        d|d      y | |t        d|d	      y )
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_methodss        r   r,   r,      s     ?&&76*,JK\J]]^_``"+'z 2^ ^  # (O,G+)& 4\ \  -Hr   c                     ddl m} | j                  D cg c]  }t        ||      s| }}|rt	        d      y c c}w )Nr   r<   zqTrainer is already configured with a `LearningRateFinder` callback.Please remove it if you want to use the Tuner.)r@   r=   r0   
isinstancerY   )r   r=   r3   configured_callbackss       r   r?   r?      sL    H)0):):a):2jM_>`B):a=
 	
  bs   ;;c                     | j                   j                  rt        d      ddlm} | j
                  D cg c]  }t        ||      s| }}|rt        d      y c c}w )NzMTuning the batch size is currently not supported with distributed strategies.r   r*   znTrainer is already configured with a `BatchSizeFinder` callback.Please remove it if you want to use the Tuner.)_accelerator_connectoris_distributedrY   r.   r+   r0   r\   )r   r+   r3   r]   s       r   r-   r-      si    %%44hii N)0):):^):2j_>]B):^=
 	
  _s   AA)NNNr   rD   )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   r,   r?   r-   rV   r   r   <module>rh      s    ; :  9 L Q;j- j-\ W[26.2<A	&79Q&Q RS./ *+ 89	
 
0	

r   