
    Pi                        d dl Z d dlZd dlmZ d dlmZmZmZmZ d dl	m
Z
 d dlZd dlmZ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mZ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% d dl&m'Z' d dl(m(Z(  ej)        d          Z* G d de"          Z+ej,        deddfd            Z-e.dk    r e j/         e-                       dS dS )    N)partial)AnyDictOptionalUnion)warn)
DictConfig
ListConfig)nn)	Optimizer)StatefulDataLoader)StatefulDistributedSampler)configmodulestrainingutils)_get_component_from_path)padded_collate_packed)ConcatDataset)FTRecipeInterface)DummyProfilerPROFILER_KEY)get_lr)tqdmDEBUGc                      e Zd ZdZdeddfdZdedeeef         fdZ	deeef         ddfd	Z
deddfd
Z	 d(dee         deej        j        ef         fdZdededededeeef         dej        fdZ	 	 d)dededeeeef                  dee         fdZdee         dededee         fdZ	 d(dedededed eeeef                  defd!Zd"eddfd#Zd$eeej        f         dej        fd%Zd*d&Z d*d'Z!dS )+FullFinetuneRecipeSingleDeviceaG  
    Full finetuning recipe for dense transformer-based LLMs such as Llama2. This recipe is optimized
    for single GPU training. Training on CPU is not supported.

    Features:
        - Activation Checkpointing. This can be controlled using the ``enable_activation_checkpointing``
            flag. Activation checkpointing helps reduce the memory footprint since we no longer keep
            activations in memory and instead recompute them during the backward pass. This is especially
            helpful for larger batch sizes when you're memory constrained. But these savings in memory
            come at the cost of training performance. In most cases training can slow-down quite a bit as
            a result of this activation recomputation.

        - Activation Offloading. This can be controlled using the ``enable_activation_offloading``
            flag. Activation offloading is a technique similar to activations checkpointing that helps
            reduce the memory footprint to prevent OOMs on CUDA and enable bigger batches. Where activations
            checkpointing drops the activation in the forward to recompute it later in the backward,
            activations offloading will drop the activation in the forward to the CPU and bring it
            back during the backward pass. As always, there is a tradeoff--these savings in memory can
            come at the cost of training performance and CPU resources. To recover some runtime cost,
            we've added an option to enable offloading on a different stream to permit overlapping with
            the computation. This option is currently only available on PyTorch 2.5 or later and will
            be enabled by default if an acceptable torch version is found. Activation offloading can be
            used in conjunction with activation checkpointing.

        - Precision. Full fp32 and bf16 training are supported. Precision is controlled using the ``dtype``
            flag. When ``dtype=bf16``, all activations, gradients and optimizer states are in bfloat16. In
            most cases this should halve the memory footprint of full precision (fp32) training, without
            loss in model quality (will depend on the model, training data and other settings). For
            GPUs which do not support bfloat16, we fall back to fp32. Mixed precision training and fp16
            precision are currently not supported.

        - Gradient Accumulation. You can simulate larger batch sizes by accumulating gradients. This is
            controlled using the ``gradient_accumulation_steps`` flag.

                Total Batch Size = batch_size * gradient accumulation steps.

            For example: with batch_size=1 and gradient_accumulation_steps=32 we get a total batch size of 32.

            Gradient accumulation is especially useful when you are memory constrained. In this case,
            accumulating gradients might give you better training speed than enabling activation
            checkpointing.

        - Optimizer in Backward. Fusing the optimizer step into the backward pass helps reduce the memory
            footprint associated with gradients. This can be especially helpful when you are memory
            constrained. Note that users can only use ONE of gradient accumulation or optimizer in backward.
            These features currently do not work together. For more details on optimizer in backward, please
            see this tutorial: https://pytorch.org/tutorials/intermediate/optimizer_step_in_backward_tutorial.html

        - Lower precision optimizers. This recipe supports lower-precision optimizers from the bitsandbytes
            library (https://huggingface.co/docs/bitsandbytes/main/en/index). We've tested the recipe with
            8-bit AdamW and Paged AdamW. These optimizers are especially helpful when you are memory constrained
            since they help reduce the memory footprint associated with the optimizer states.

        - Checkpointing. Model weights are checkpointed both at the end of each epoch and at the end of
            training. Optimizer State and recipe state (seed, total_epochs, number of epochs run etc) are
            only saved at the end of a given epoch and used in case of resuming training.

            Resuming training is controlled by the ``resume_from_checkpoint`` flag. Mid-epoch checkpointing is
            currently not supported.

            For more details on the checkpointer, please take a look at
            our checkpointer deepdive (https://pytorch.org/torchtune/main/deep_dives/checkpointer.html).

        - Logging. Terminal, Disk, WandB and TensorBoard are all supported.

        - Gradient Clipping. Gradient clipping is supported using the ``clip_grad_norm`` flag. By default,
            ``clip_grad_norm`` is set to ``None``. If you only want to log the grad norm, you can set
            ``clip_grad_norm='inf'``.

    For a full list of example configs for this recipe, run ``tune ls`` on the command line. Each config
    has example commands for how to kick-off training.

    Args:
        cfg (DictConfig): OmegaConf object parsed from yaml file

    Raises:
        ValueError: If ``dtype`` is set to fp16.
        RuntimeError: If ``dtype`` is set to bf16 and the hardware does not support bf16.
        RuntimeError: If ``gradient_accumulation_steps > 1`` and ``optimizer_in_bwd`` is `True`.
        RuntimeError: If ``left_pad_sequence`` is set as the data collator.
        RuntimeError: If ``enable_activation_offloading`` is True and device is not CUDA.
        RuntimeError: If ``enable_activation_offloading`` is True and ``enable_activation_checkpointing`` is False.
    cfgreturnNc                    t          j        |j                  | _        t	          j        |j        | j                  | _        | j        t          j	        k    rt          d          |j        | _        |                    dd          | _        |                    dd          | _        | j        r1| j        j        dk    r!t"                              d           d| _        |j        | _        |j        | _        |j        | _        |                    d	d           | _        | j        r0| j        t5          d
          | j        dk    rt5          d          |                    dd          | _        |                    dd          | _        | j        r6| j        j        dk    rt5          d          | j        st5          d          n1| j        r*|j        j        dk    rt          j        t"          d           t	          j         |j!        |                    dd                     | _!        d| _"        |j#        | _$        |j%        | _%        d| _&        d S )NdevicezVfull fp16 training is not supported with this recipe. Please use bf16 or fp32 instead.log_every_n_steps   log_peak_memory_statsFcpuzglog_peak_memory_stats was set to True, however, training uses cpu. Setting log_peak_memory_stats=False.clip_grad_normzsGradient clipping is not supported with optimizer in bwd.Please set clip_grad_norm=None, or optimizer_in_bwd=False.zGradient accumulation is not supported with optimizer in bwd.Please set gradient_accumulation_steps=1, or optimizer_in_bwd=False.enable_activation_checkpointingenable_activation_offloadingcudazFenable_activation_offloading should only be True when training on CUDAz]enable_activation_offloading should only be True when enable_activation_checkpointing is TrueLLAMA3_VISIONzHint: enable_activation_checkpointing is True, but enable_activation_offloading isn't. Enabling activation offloading should reduce memory further.cudnn_deterministic_mode)seed
debug_moder   )'r   
get_devicer"   _devicer   	get_dtypedtype_dtypetorchfloat16
ValueError
output_dir_output_dirget_log_every_n_steps_log_peak_memory_statstypeloginforesume_from_checkpoint_resume_from_checkpointgradient_accumulation_steps_gradient_accumulation_stepsoptimizer_in_bwd_optimizer_in_bwd_clip_grad_normRuntimeError _enable_activation_checkpointing_enable_activation_offloadingcheckpointer
model_typelog_rank_zeroset_seedr-   
epochs_runepochstotal_epochsmax_steps_per_epochglobal_step)selfr   s     w/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/recipes/full_finetune_single_device.py__init__z'FullFinetuneRecipeSingleDevice.__init__w   s   'sz:::(4<HHH ;%-''h  
 >"%''*=q"A"A&)gg.Eu&M&M#& 	04<+<+E+EHHy   +0D' (+'A$,/,K)!$!5"ww'7>> ! 
	#/"Q   0144"[   14-u1
 1
- .1WW*E.
 .
* - 	| F**"\   8 "s  
 1	 +>>O   %cgg.H$&O&O
 
 
	 J#&#:     cfg_checkpointerc                     t          j        || j                  | _        | j                                        }| j        r|                     |           |S )z
        Extract the checkpoint state from file and validate. If resume_from_checkpoint
        is True, this also includes the recipe state.
        )should_load_recipe_state)r   instantiater@   _checkpointerload_checkpoint_update_recipe_state)rR   rV   checkpoint_dicts      rS   r[   z.FullFinetuneRecipeSingleDevice.load_checkpoint   sb    
 $/%)%A
 
 
 ,<<>>' 	7%%o666rU   	ckpt_dictc                 8   	 |t           j                 | _        | j        |t           j                 k    r:t          d|t           j                             |t           j                 | _        | j        |t           j                 k    r:t          d|t           j                             |t           j                 | _        | j        |t           j	                 k    rt          d| j                    dS dS # t          $ r}t          d          |d}~ww xY w)z;
        Updates the recipe state from checkpoint.
        zWConfig value for seed does not match the checkpoint value, using the checkpoint value: )messagezfConfig value for max_steps_per_epoch does not match the checkpoint value, using the checkpoint value: z[Config value for total_epochs does not match the checkpoint value, using the config value: zCheckpoint does not contain the required keys needed for updating recipe state. Are you sure you passed in the right recipe checkpoint?N)r   
EPOCHS_KEYrM   r-   SEED_KEYr   rP   MAX_STEPS_KEYrO   TOTAL_EPOCHS_KEYKeyError)rR   r^   es      rS   r\   z3FullFinetuneRecipeSingleDevice._update_recipe_state   sf   "	'(;<DO yIh&7888V7@AR7SV V    &h&78	'9X5K+LLL[7@AW7X[ [    ,5X5K+L(  Ih.G$HHHG373DG G      IH  	 	 	J  	s   C4C: :
DDDc                 \   t          j        |j                  | _        | j                            |           |                     |j                  }|j        | _        |j	        dk    r|j        rt          d          |                     |j        | j        | j        | j        |t          j                           | _        t          j        |j                  | _        t(                              d           |                     |j        |j        | j        r|t          j                 nd          | _        t          j        |j                  | _        | j        rt          j        | j                   | j        j        j         dk    r$| j        !                    | j        j"                   t(                              d           |#                    d	d
          }| $                    |j%        |j&        |j'        || j        r|t          j(                 nd          | _)        tU          | j)                  | j+        z  | _,        | j-        | j-        | j,        k     r| j-        | _,        | j.        | j,        z  | _/        | 0                    |#                    dd          | j1        | j,        z  | j/        dz
            | _2        | 3                    |#                    th          d                    | _5        tm          j7        |j'        df| j        j8        | j9                  | _:        dS )z
        Sets up the recipe state correctly. This includes setting recipe attributes based
        on the ``resume_from_checkpoint`` flag.
        npuzRNPU does not support model compilation. Please set `compile: False` in the config.)	cfg_modelr(   r)   compile_modelmodel_state_dictz#Tokenizer is initialized from file.N)cfg_optimizerrC   opt_state_dictCEWithChunkedOutputLosszLoss is initialized.
collate_fnz!torchtune.data.padded_collate_sft)cfg_datasetshuffle
batch_sizero   dataloader_state_dictlr_schedulerr$   )cfg_lr_schedulernum_training_steps
last_epochr!   );r   rY   metric_logger_metric_logger
log_configr[   rI   compile_compiler"   r6   _setup_modelmodelrG   rH   r   	MODEL_KEY_model	tokenizer
_tokenizerr=   r>   _setup_optimizer	optimizerrC   r@   OPT_KEY
_optimizerloss_loss_fncompile_loss	__class____name__set_num_output_chunksnum_output_chunksr9   _setup_datadatasetrq   rr   DATALOADER_KEY_dataloaderlenrB   _steps_per_epochrP   rM   rQ   _setup_lr_schedulerrO   _lr_scheduler_setup_profilerr   	_profilerr4   fullignore_indexr0   ignore_labels_cache)rR   r   r^   collate_names       rS   setupz$FullFinetuneRecipeSingleDevice.setup   s   
 %01BCC 	&&s+++(()9::	
 :3;d   ''i,0,Q)-)K-&x'9: ( 
 
 !,S];;6777 //- 1/3/KU	(*++QU	 0 
 
 *3844= 	1!$-000="+/HHHK--dm.MNNN'((( ww|-PQQ++K~# /	(122 , 

 

(  !!T%FF 	 $0(4+@@@$($<D!?T-BB "55 WW^T::#043HH'!+ 6 
 
 --cgglD.I.IJJ $):^Q!;DL$
 $
 $
   rU   cfg_profilerc                    |t          ddi          }|                    dd          d|d<   n#|                    d          dk    s
J d            t          j        |          \  }}t                              d|            |                    dd          | _        |d         r'|d	         | _        |d
         | _        |d         | _	        |S )a  
        Parses the `profiler` section of top-level `cfg` and sets up profiler

        Args:
            cfg_profiler (Optional[DictConfig]): ``profiler`` section of the top-level ``cfg`` (the main config passed to
                `recipe.main`). Default None.

        Returns:
            profiler: Union[torch.profiler.profile, DummyProfiler] - DummyProfiler is a nullcontext with no-op methods
            for `start`, `stop`, and `step` that can be used in place of `torch.profiler.profile` if profiler is not enabled such
            that the instrumented training loop does not need to be changed profiling is disabled.

        The profiler config can be provided in configs under the `profiler` key with the following layout:

        .. code-block:: yaml
            profiler:
                enabled: bool

                #Output directory of trace artifacts
                output_dir: str

            #`torch.profiler.ProfilerActivity` types to trace
            cpu: bool
            cuda: bool

                #Trace options
                profile_memory: bool
                with_stack: bool
                record_shapes: bool
                with_flops: bool

            # `torch.profiler.schedule` options:
            # wait_steps -> wait, warmup_steps -> warmup, active_steps -> active, num_cycles -> repeat
            wait_steps: int
            warmup_steps: int
            active_steps: int
            num_cycles: int
        NenabledF_component_z'torchtune.training.setup_torch_profilerzdOnly torch profiler supported currently: component must be `torchtune.training.setup_torch_profiler`z& Profiler config after instantiation: profile_memory
wait_stepswarmup_stepsactive_steps)
r	   r9   r   rY   r=   r>   profiler_profile_memoryprofiler_wait_stepsprofiler_warmup_stepsprofiler_active_steps)rR   r   profilerprofiler_cfgs       rS   r   z.FullFinetuneRecipeSingleDevice._setup_profiler^  s    V %y%&899L M4008*SL''   //<= = =u= = = "(!3L!A!A,H,HHIII'3'7'78H%'P'P$	" 	F'3L'AD$)5n)ED&)5n)ED&rU   ri   r(   r)   rj   rk   c                    t          j        | j                  5  | j        5  t	          j        |          }ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |rt          j        |           |r!t          j        |t          j	        h           |
                    |           t          j        |                                | j                   t          j        ||          | _        t                              d| j         d           | j        j        dk    r.t          j        | j                  }t          j        |           |S )zO
        Set up the model including enabling activation checkpointing.
        N)auto_wrap_policy)r2   z$Model is initialized with precision .r&   r!   )r   set_default_dtyper3   r0   r   rY   rj   set_activation_checkpointingr   TransformerSelfAttentionLayerload_state_dictvalidate_expected_param_dtypenamed_parametersget_act_offloading_ctx_manageractivations_handling_ctxr=   r>   r<   get_memory_statslog_memory_stats)rR   ri   r(   r)   rj   rk   r~   memory_statss           rS   r}   z+FullFinetuneRecipeSingleDevice._setup_model  s    '44 	2 	2dl 	2 	2&y11E	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2  	*"5)))* 	1)N(O    	./// 	.""$$DK	
 	
 	
 	

 )1(O/)
 )
% 	FFFFGGG<%%#4DLIIIL%l333s3   AAAA	A
A	AA!AFrl   rC   rm   c                 >   |rfd| j                                         D             }t          j        | j         |           t          j        | j         |          | _        |>	 | j                            |           n"# t          $ r}t          d          |d}~ww xY wt          
                    d           dS t          j        | j                                                   }|r|                    |           t          
                    d           |S )zp
        Set up the optimizer. This method also handles loading the optimizer state_dict, if specified.
        c                 >    i | ]}|t          j        |g          S  )r   rY   ).0prl   s     rS   
<dictcomp>zCFullFinetuneRecipeSingleDevice._setup_optimizer.<locals>.<dictcomp>  s:        6%maS99  rU   )r~   
optim_dictNzzFailed loading in-backward optimizer checkpoints.Please make sure run being restored from was using in-backward optimizer.z"In-backward optimizers are set up.zOptimizer is initialized.)r   
parametersr   register_optim_in_bwd_hookscreate_optim_in_bwd_wrapper_optim_ckpt_wrapperr   BaseExceptionrF   r=   r>   r   rY   )rR   rl   rC   rm   r   rf   r   s    `     rS   r   z/FullFinetuneRecipeSingleDevice._setup_optimizer  s[     !	   //11  J
 0kj    (0'Kkj( ( (D$ ),<<^LLLL$   &d  
 HH9:::4*=$+:P:P:R:RSSI :)).999HH0111s   'B 
B!BB!ru   rv   rw   c                 v   |t                               d           dS | j        r9t          t	          | j        j                                                            }n| j        }t          j
        ||||          }| j        r| j                            |           t                               d           |S )aH  
        Set up the learning rate scheduler based on the provided configuration.
        It handles both standard optimization and optimizer-in-backward cases, and supports
        schedulers from both torchtune.modules and torch.optim.

        Args:
            cfg_lr_scheduler (Optional[DictConfig]): The learning rate scheduler configuration.
            num_training_steps (int): The total number of training steps.
            last_epoch (int): The index of the last epoch.

        Returns:
            lr_scheduler (Optional[Optimizer]): The learning rate scheduler.
        NzDNo learning rate scheduler configured. Using constant learning rate.)rv   rw   z'Learning rate scheduler is initialized.)r=   r>   rD   nextiterr   	optim_mapvaluesr   r   rY   set_lr_scheduler)rR   ru   rv   rw   r   rt   s         rS   r   z2FullFinetuneRecipeSingleDevice._setup_lr_scheduler  s    & #HHV   4! 	(T$":"D"K"K"M"MNNOOII I )1!	
 
 
 ! 	D$55lCCC:;;;rU   rp   rq   rr   ro   rs   c           
          t          |t                    r0 fd|D             }t          |          }t          |dd          }n0t	          j        | j                  }|                    dd          }d|v rt          d          t          |          }t          |dd|d	          }	t          |||	|s&t          | j        j         j        j        
          nt           d          }
|
S )z
        All data related setup happens here. This recipe currently supports only
        map-style datasets. If a state_dict is provided (meaning we are resuming a training run),
        it is loaded into the dataloader.
        c                 D    g | ]}t          j        |j                  S r   )r   rY   r   )r   single_cfg_datasetrR   s     rS   
<listcomp>z>FullFinetuneRecipeSingleDevice._setup_data.<locals>.<listcomp>4  s9       & "#5tGG  rU   )datasetspackedFleft_pad_sequencez1left_pad_sequence collator is only for inference.r$   r   )num_replicasrankrq   r-   )padding_idx
ignore_idxT)r   rr   samplerro   	drop_last)
isinstancer
   r   getattrr   rY   r   r9   rF   r   r   r   r   pad_idr   r   r   )rR   rp   rq   rr   ro   rs   r   dsr   r   
dataloaders   `          rS   r   z*FullFinetuneRecipeSingleDevice._setup_data&  s;    k:.. 		6   *5  H 111BR511FF#KAAB __Xu55F *,,RSSS-j99
,
 
 
 (! + $ 6#}9    + 
 
 

" rU   epochc                 ^   t           j        | j                                        i}|dz   | j        k     r|                    t           j        | j        t           j        | j	        t           j
        | j        t           j        | j        t           j        | j                                        i           | j        s'| j                                        |t           j        <   n&| j                                        |t           j        <   | j                            |||dz   | j        k                dS )z
        Save state dict to file. The recipe save_checkpoint method is responsible for
        correctly creating the checkpoint dict and passing to the checkpointer.
        r$   )r   intermediate_checkpointN)r   r   r   
state_dictrO   updaterb   r-   ra   rM   rd   rc   rP   r   r   rD   r   r   r   rZ   save_checkpoint)rR   r   r^   s      rS   r   z.FullFinetuneRecipeSingleDevice.save_checkpoint]  s   
 ')?)?)A)AB	19t(((%ty'-t/@*D,D+T-=-H-H-J-J   ) T.2o.H.H.J.J	(*++.2.F.Q.Q.S.S	(*+**%*QY1B%B 	+ 	
 	
 	
 	
 	
rU   batchc                    |                     d          }| j        5   | j        di |}d d d            n# 1 swxY w Y   t          j        |ddd f         | j        d |j        d                  f          }t          |t                    s>|	                    d          }|	                    d|
                    d                    }|                     ||          }~|S )Nlabels.r$   r   r   )popr   r   r4   hstackr   shaper   listreshapesizer   )rR   r   r   logitsr   s        rS   
_loss_stepz)FullFinetuneRecipeSingleDevice._loss_stepx  s"   8$$* 	* 	* T[))5))F	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* CG_d67Ha7HIJ
 
 &$'' 	9^^B''F^^BB88F }}VV,,s   7;;c           	      P	   | j         rt                              d           | j        s| j                                         t          j                    }d}d}| j        	                                 t          | j        | j                  D ]}t          | j                  }| j        j                            |           t%          | j                  D ]\  }}|dk    rM| j        rF|| j        | j        z   k    r3| j        j        dk    r#t0          j        j                                         t9          j        || j                   |d         | j        j        k                                     }||z  }| !                    |          |z  }	||	z  }|	"                                 |dz   | j#        z  dk    r| j        stI          j%        | j&        d|z             | j'        Ot0          j(        j        )                    | j&        *                                tW          | j'                            }
| j        ,                                 | j                            d	
           | j-        | j-        ,                                 | xj.        dz  c_.        |/                                |z  }|0                    d           |1                    |dz    d| j.         d|            | j.        | j2        z  dk    rt          j                    |z
  }|tg          | j        s| j        n| j4                  ||z  d}| j        j        dk    r4| j5        r-|0                    tI          j6        | j                             | j'        |0                    d|
i           | j7        8                    || j.                   d}d}t          j                    }|dk    rW| j        rP|| j        | j        z   | j9        z   k    r5| j        j        dk    r%t0          j        j                            d           | j        ,                                 |dz   | j#        z  | j:        k    r n| xj        dz  c_        | ;                    |           | j        <                                 dS )z
        The core training loop. Supports training on subsets of the dataset using the
        ``max_steps_per_epoch``.
        zpNOTE: torch.compile is enabled and model is compiled in first forward. Expect a relatively slow first iteration.r   )totalr*   r   r$   N)max_normT)set_to_none|z|Loss: )r   lrtokens_per_second_per_gpur&   r!   	grad_norm)step)r   )r   )=r|   r=   r>   rD   r   	zero_gradtimeperf_counterr   startrangerM   rO   r   r   r   r   	set_epoch	enumerater   r   r   r0   r<   r4   r*   memory_record_memory_historyr   batch_to_devicer   r   sumr   backwardrB   r   scale_gradsr   rE   r   clip_grad_norm_r   floatr   r   rQ   itemr   set_descriptionr:   r   r   r;   r   ry   log_dictr   rP   r   stop)rR   t0running_loss
num_tokens
curr_epochpbaridxr   current_num_tokenscurrent_lossr   loss_to_logtime_per_stepr	  s                 rS   trainz$FullFinetuneRecipeSingleDevice.train  s   
 = 	HH C   % 	(O%%'''   
1BCC j	3 j	3Jd3444D$..z:::'(899 d d
U !OO4 $t7$:TTTT)V33J%<<>>>%eT\:::
 (Ot}'AA#%% # 00
  $u558JJ,%%''' !Gt@@AEE1 D ,T[!j.III/;(-(F(F $ 6 6 8 8).t/C)D)D )G ) )I ,,...11d1CCC )5*//111$$)$$"."3"3"5"5
"BKKKNNN((%>RRD,<RR[RR  
 '$*AAQFF(,(9(;(;b(@$/ #) ,0+A%BDOO)-)A	# # :Dm9S$ $  <,55$:U5$OO ( 9 N N N    /;$OO[),DEEE+44$!%!1 5    $%L!"J*,,B !OO4 $/01011 1 )V33J%<<T<JJJ
 ##%%% 1W!BB-. . E.
 OOq OO  z 2222rU   c                 8    | j                                          d S N)ry   close)rR   s    rS   cleanupz&FullFinetuneRecipeSingleDevice.cleanup  s    !!#####rU   r  )FN)r   N)"r   
__module____qualname____doc__r	   rT   r   strr   r[   r\   r   r   r   r4   r   profiler   r   boolr   Moduler}   r   r   intr   r   r   r   Tensorr   r  r  r   rU   rS   r   r   "   s       R RhJJ J4 J J J JX
 tCH~    &d38n & & & & &Pb
 b
 b
 b
 b
 b
J 48A A$Z0A	u~%}4	5A A A AF(( *.( '+	(
 ( sCx.( 
( ( ( (Z "'37	* *!* * !c3h0	*
 
)	* * * *X-":.-  - 	-
 
)	- - - -j ;?5 55 5 	5
 5  (S#X75 
5 5 5 5n
S 
T 
 
 
 
6S%,%6 7 EL    0@ @ @ @D$ $ $ $ $ $rU   r   r   r   c                     t          j        d|            t          |           }|                    |            |                                 |                                 dS )z
    Entry point for the recipe.

    Configurable parameters are read in the following order:
        - Parameters specified in config (see available configs through ``tune ls``)
        - Overwritten by arguments from the command-line
    r   )recipe_namer   )r   N)r   rz   r   r   r  r  )r   recipes     rS   recipe_mainr&    sb     "BLLLL+444F
LLSL
LLNNN
NNrU   __main__)0sysr   	functoolsr   typingr   r   r   r   warningsr   r4   	omegaconfr	   r
   r   torch.optimr   torchdata.stateful_dataloaderr   %torchdata.stateful_dataloader.samplerr   	torchtuner   r   r   r   torchtune.config._utilsr   torchtune.datar   torchtune.datasetsr   torchtune.recipe_interfacesr   torchtune.trainingr   r    torchtune.training.lr_schedulersr   r   
get_loggerr=   r   parser&  r   exitr   rU   rS   <module>r:     s   


        - - - - - - - - - - - -        , , , , , , , ,       ! ! ! ! ! ! < < < < < < L L L L L L 6 6 6 6 6 6 6 6 6 6 6 6 < < < < < < 0 0 0 0 0 0 , , , , , , 9 9 9 9 9 9 : : : : : : : : 3 3 3 3 3 3       ewq$ q$ q$ q$ q$%6 q$ q$ q$h Z D     zCH[[]] rU   