
    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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mZ d dlmZ d d	lmZmZ d d
lmZmZmZmZ d dlm Z m!Z! d dl"m#Z# d dl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, d dl-m.Z. d dl/m0Z0m1Z1 d dl2m2Z2  ej3        d          Z4 G d de.          Z5ej6        deddfd            Z7e8dk    r e j9         e7                       dS dS )    N)partial)AnyDictListOptionalTupleUnion)warn)
DictConfig
ListConfig)nn)destroy_process_groupinit_process_group)	Optimizer)
DataLoaderDistributedSampler)configmodulestrainingutils)padded_collate_packedpadded_collate_sft)ConcatDataset)
DoRALinearget_adapter_paramsget_adapter_state_dictget_lora_module_namesget_merged_lora_ckpt
LoRALinearset_trainable_params(validate_missing_and_unexpected_for_lora)FTRecipeInterface)DummyProfilerPROFILER_KEY)tqdmDEBUGc                   z   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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+dededededeeef         deee                  deeeef                  dej        fdZdedeee                  dededeeef         dej        fdZ	 d*dedeeeef                  defdZdedededefdZd ed!ed"edeee f         fd#Z!d$eddfd%Z"d&eeej#        f         dej#        ej#        ffd'Z$d,d(Z%d,d)Z&dS )-KDRecipeDistributeda  
    Knowledge distillation recipe for dense transformer-based LLMs such as Llama3. This recipe is optimized
    for single GPU training. Training on CPU is not supported.

    Features:
        - FSDP. Supported using PyTorch's FSDP APIs. CPU offload of parameters, gradients, and optimizer states
            is supported via ``fsdp_cpu_offload``. Resharding of parameters after the forward pass is
            done by default (corresponding to FULL_SHARD sharding strategy), but can be disabled by setting the config
            ``fsdp_reshard_after_forward`` to False (this corresponds to SHARD_GRAD_OP sharding strategy).
            DDP is currently not supported. Training on CPU is not supported.

        - Activation Checkpointing. This can be controlled using the ``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.

        - 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.

        - Checkpointing. Model weights are checkpointed both at the end of each epoch and at the end of
            training. Currently we checkpoint both the adapter weights (trainable params only) and the
            complete merged weights (adapter weights added back to the base model). For more details
            please take a look at our LoRA tutorial
            (https://pytorch.org/torchtune/main/tutorials/lora_finetune.html).

            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/tutorials/checkpointer.html).

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

    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.

    cfgreturnNc                 "   t          j        |j                  | _        t	          j        |j        | j                  | _        | j        t          j	        k    rt          d          t          j                    \  | _        | _        | j        dk    | _        |j        | _        |                    dd          | _        |                    dd          | _        |j        | _        t	          j        |j        |                    dd           	          | _        d| _        |j        | _        |j        | _        d| _        |j        | _        |                    d
d          | _        |j         | _!        |                    dd          | _"        d S )NdevicezHfp16 precision is not supported in this recipe. Please use fp32 or bf16.r   log_every_n_steps   log_peak_memory_statsFcudnn_deterministic_mode)seed
debug_modesave_adapter_weights_onlykd_ratiog      ?)#r   
get_devicer-   _devicer   	get_dtypedtype_dtypetorchfloat16
ValueErrorget_world_size_and_rank
world_sizerank_is_rank_zero
output_dir_output_dirget_log_every_n_steps_log_peak_memory_statsenable_activation_checkpointing _enable_activation_checkpointingset_seedr2   
epochs_runepochstotal_epochsmax_steps_per_epochglobal_stepresume_from_checkpoint_resume_from_checkpoint_save_adapter_weights_onlygradient_accumulation_steps_gradient_accumulation_steps	_kd_ratio)selfr)   s     ~/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/recipes/knowledge_distillation_distributed.py__init__zKDRecipeDistributed.__init__l   se   'sz:::(4<HHH ;%-''Z   &+%B%D%D"!Y!^ >"%''*=q"A"A&)gg.Eu&M&M# 140S- %cgg.H$&O&O
 
 
	 J#&#: '*'A$*-''2Mu*U*U',/,K)S11    cfg_checkpointerc                     t          j        || j                  | _        | j                                        }| j        r2t
          j        |vrt          d          |                     |           |S )z
        Extract the checkpoint state from file and validate. This includes the
        base model weights. If resume_from_checkpoint is True, this also includes
        the adapter weights and recipe state
        )should_load_recipe_statezPAdapter weights not found. Please ensure a valid adapter checkpoint is provided.)	r   instantiaterP   _checkpointerload_checkpointr   ADAPTER_KEYr=   _update_recipe_state)rU   rY   checkpoint_dicts      rV   r^   z#KDRecipeDistributed.load_checkpoint   s     $/%)%A
 
 
 ,<<>>' 	7#?:: f  
 %%o666rX   c                 V    t          j        |          }|                                }|S )zA
        Extract the teacher checkpoint state from file.
        )r   r\   r^   )rU   rY   teacher_checkpointerra   s       rV   load_teacher_checkpointz+KDRecipeDistributed.load_teacher_checkpoint   s3      &1 
  
 />>@@rX   	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_KEYrJ   r2   SEED_KEYr
   rM   MAX_STEPS_KEYrL   TOTAL_EPOCHS_KEYKeyError)rU   re   es      rV   r`   z(KDRecipeDistributed._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           	         | j         r8t          j        |j                  | _        | j                            |           |                    dd          | _        |                     |j	                  }| 
                    |j                  }|                     |j        |j        |                    dd          |                    dd          |t          j                 | j        r|t          j                 nd          | _        |                     |j        |                    d	d          |                    dd          |                    dd          |t          j                 
          | _        t          j        |j                  | _        t3          j        t6          d           |                     |j        | j        r|t          j                 nd          | _        t          j        |j                   | _!        t          j        |j"                  | _#        | j        rJt          j$        | j!        | j                   | _!        t          j$        | j#        | j                   | _#        | j!        j%        j&        dk    rl| j        '                    | j!        j(                   | j        '                    | j!        j(                   | j!        j(        | j#        j(        k    s
J d            t3          j        t6          d           | )                    |j*        |j+        |j,                  \  | _-        | _.        t_          | j.                  | j0        z  | _1        | j2        0| j2        | j1        k     r | j2        | _1        | j3        | j1        z  | _4        | 5                    |j6        | j7        | j1        z  | j4        dz
            | _8        | 9                    |                    tt          d                    | _;        ty          j=        |j,        df| j!        j>        | j?                  | _@        dS )z
        Setup the recipe state. This includes recipe state (if resume_from_checkpoint is True),
        model, tokenizer, loss, optimizer, learning rate scheduler, sampler, and dataloader.
        compileF)rY   fsdp_cpu_offloadfsdp_reshard_after_forwardTN)	cfg_modelrG   rq   reshard_after_forwardbase_model_state_dictlora_weights_state_dictcustom_sharded_layers)	model_cfgrw   rq   rt   model_state_dictz#Tokenizer is initialized from file.)cfg_optimizeropt_state_dictverboseCEWithChunkedOutputLosszDNumber of output chunks for loss_fn and kd_loss_fn must be the same.zLoss is initialized.)cfg_datasetshuffle
batch_sizer/   )cfg_lr_schedulernum_training_steps
last_epochr,   )ArA   r   r\   metric_logger_metric_logger
log_configrD   _compiler^   checkpointerrd   rc   _setup_modelmodelrG   r   	MODEL_KEYrP   r_   _model_setup_teacher_modelteacher_model_teacher_model	tokenizer
_tokenizerr   log_rank_zerolog_setup_optimizer	optimizerOPT_KEY
_optimizerloss_loss_fnkd_loss_kd_loss_fncompile_loss	__class____name__set_num_output_chunksnum_output_chunks_setup_datadatasetr   r   _sampler_dataloaderlenrS   _steps_per_epochrM   rJ   rN   _setup_lr_schedulerlr_schedulerrL   _lr_scheduler_setup_profilerr$   	_profilerr;   fullignore_indexr7   ignore_labels_cache)rU   r)   ra   teacher_checkpoint_dicts       rV   setupzKDRecipeDistributed.setup   s   
  	0"("4S5F"G"GD **3///	511..@P.QQ"&">"> 5 #? #
 #

 ''i,/,O WW%7??"%''*F"M"M"1(2D"E / 455 ( 
 
 #77'"%''*A4"H"H WW%7??"%''*F"M"M4X5GH 8 
 
 !,S];;C!FGGG//- / 011 0 
 
 *3844!-ck::= 	$1t'9  DM  (4 $*<     D ="+/HHHK--dm.MNNN55dm6UVVV /43C3UUUUU VUU 	C!7888 +/*:*:K~ +; +
 +
't'  !!T%FF 	 $0(4+@@@$($<D!#1FFD "55 -#043HH'!+ 6 
 
 --cgglD.I.IJJ $):^Q!;DL$
 $
 $
   rX   cfg_profilerc                    |t          ddi          }|                    dd          d|d<   n#|                    d          dk    s
J d            t          j        |          \  }}t	          j        t          d|            | j        rJ|                    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   rD   r   r\   r   r   r   rA   profiler_profile_memoryprofiler_wait_stepsprofiler_warmup_stepsprofiler_active_steps)rU   r   profilerprofiler_cfgs       rV   r   z#KDRecipeDistributed._setup_profilerM  s   V %y%&899L M4008*SL''   //<= = =u= = = "(!3L!A!A,H,HH	
 	
 	
  	J+7+;+;<Le+T+TD(I& J+7+E(-9.-I*-9.-I*rX   rs   rG   rq   rt   ru   rw   rv   c           	         |j         | _        |j        | _        t	          |j                  | _        |j        | _        t          |dd          | _
        t          j        t          d           t          j                    }t!          j        | j                  5  t'          j        d          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   t/          |	          | _        t3          |	| j                   | j        rt!          j        |	| j                   |r!t!          j        |	t<          j        h           tA          t           j!        |          g}
t!          j"        |	|
||	           |r!t!          j#        |	|| j$        |
          \  }}nd\  }}t!          j        | j                  5  | j$        5  |rdn| j$        }|	                                D ]|}tK          |tL                    stK          |tN                    r,|s*|(                    |           |)                                 tU          |d          r|+                                 }	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t!          j#        |	|| j$        |
          \  }}|	                                D ]&}tU          |d          r|,                                 't[          | j        | j        | j
        ||||           t!          j.        |	           t          j        t          dt          j                    |z
  dd           | j        r0t!          j/        | j$                  }t!          j0        |d           t&          j1        2                                 |	S )a  
        Model initialization has some important considerations:
          a. To minimize GPU peak memory, we initialize the model on meta device with
             the right dtype
          b. All ranks calls ``load_state_dict`` without peaking CPU RAMs since
             full state dicts are loaded with ``torch.load(mmap=True)``
          c. We register (pre-)forward hooks with ``fully_shard`` instead of wrapping `nn.Module`
        apply_lora_to_outputFzIFSDP is enabled. Instantiating model and loading checkpoint on Rank 0 ...metaNr|   )auto_wrap_policynames_to_matchr   shard_conditionscpu_offloadrt   )r   NNcpur,   	rope_initinitialize_dora_magnitude)lora_attn_modulesapply_lora_to_mlpr   base_missingbase_unexpectedlora_missinglora_unexpectedz8Instantiating student model and loading checkpoint took .2f secsz&Memory stats after student model init:rg   )3	lora_rank
_lora_rank
lora_alpha_lora_alphalistr   _lora_attn_modulesr   _apply_lora_to_mlpgetattr_apply_lora_to_outputr   r   r   timeperf_counterr   set_default_dtyper:   r;   r-   r   r\   r   adapter_paramsr    r   compile_modelrA   set_activation_checkpointingr   TransformerSelfAttentionLayerr   get_shard_conditionsshard_modelload_from_full_model_state_dictr7   
isinstancer   r   to_emptyinitialize_parametershasattrr   r   r!   !validate_no_params_on_meta_deviceget_memory_statslog_memory_statsdistributedbarrier)rU   rs   rG   rq   rt   ru   rw   rv   
init_startr   fsdp_shard_conditionsr   r   lora_devicemr   r   memory_statss                     rV   r   z KDRecipeDistributed._setup_model  s   & $-$/"&y'B"C"C"+"=%,Y8NPU%V%V"W	
 	
 	
 &((
'44 	2 	2el66J6J 	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 177UD$7888= 	F"5$2DEEEE* 	1)N(O    -4  !
 	2("7		
 	
 	
 	
 # 	7,4,T',	- - -)L// -7)L/ '44 	" 	"dl 	" 	"#3E%%K]]__ 
" 
"q*--.1;Az1J1J.1.
 JJkJ222++---1k** "KKMMM
"	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" )1(P!L(	)
 )
 )
%o  	. 	.Aq566 .++---0"5"5!%!;%+%+	
 	
 	
 	
 	25999rtGXGZGZ]gGgrrrr	
 	
 	
  	#4DLIIIL%&N   
 	!!###sm   C'/CC'C	C'C	C''C+.C+JBJ;JJ	JJ	JJ"%J"rx   ry   c                    t          j        t          d           t          j                    }t          j        | j                  5  t          j	        d          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   | j        rt          j        || j                   t          t
          j        |          g}t          j        ||||           t          j        | j                  5  | j        5  |                                D ]&}	t)          |	d          r|	                                 '	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          j        ||| j        d|	           |                                 |                                D ]	}
d
|
_        
t          j        |           t          j        t          dt          j                    |z
  dd           | j        r0t          j        | j                  }t          j        |d           t          j                                         |S )ai  
        Model initialization for teacher model has some important considerations:
          a. To minimize GPU peak memory, we initialize the model on meta device with
              the right dtype
           b. All ranks calls ``load_state_dict`` without peaking CPU RAMs since
              full state dicts are loaded with ``torch.load(mmap=True)``
        zNFSDP enabled. Instantiating teacher model and loading checkpoint on Rank 0 ...r   Nr|   r   r   r   T)strictr   Fz8Instantiating teacher model and loading checkpoint took r   r   r,   z&Memory stats after teacher model init:rg   )r   r   r   r   r   r   r   r:   r;   r-   r   r\   r   r   rA   r   r   r   r7   r   r   r   r   eval
parametersrequires_gradr   r   r   r   r   )rU   rx   rw   rq   rt   ry   r   r   r   r   pr   s               rV   r   z(KDRecipeDistributed._setup_teacher_model  s     	\	
 	
 	
 &((
'44 	2 	2el66J6J 	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 = 	F"5$2DEEEE -4  !
 	2("7		
 	
 	
 	
 '44 	" 	"dl 	" 	"]]__ " "1k** "KKMMM"	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	0L(	
 	
 	
 	
 	

!!## 	$ 	$A#AOO 	25999rtGXGZGZ]gGgrrrr	
 	
 	
  	#4DLIIIL%&N   
 	!!###sl   BA=1B=B	BB	BBBE6<EE6E#	#E6&E#	'E66E:=E:rz   r{   c                     t          j        || j                                                  }|r!t	          j        | j        ||| j                   t          j        t          d           |S )NzOptimizer is initialized.)
r   r\   r   r   r   #load_from_full_optimizer_state_dictr7   r   r   r   )rU   rz   r{   r   s       rV   r   z$KDRecipeDistributed._setup_optimizer_  sm     &}dk6L6L6N6NOO	 	8	   	C!<===rX   r   r   r   c                 t    t          j        || j        ||          }t          j        t
          d           |S )N)r   r   z'Learning rate scheduler is initialized.)r   r\   r   r   r   r   )rU   r   r   r   r   s        rV   r   z'KDRecipeDistributed._setup_lr_schedulern  sE     )O1!	
 
 
 	C!JKKKrX   r   r   r   c           
      
    t          |t                    r0 fd|D             }t          |          }t          |dd          }n0t	          j        | j                  }|                    dd          }t          | j	         j
        |d          }t          ||||s+t          t           j        j         j        j                  nt          t"                              }t%          j        t(          d	           ||fS )
z
        All data related setup happens here. Currently this recipe only supports
        Map-style Datasets which fit into memory and an option for random shuffling.
        Samplers, iterable datasets, and streaming datasets are not supported.
        c                 D    g | ]}t          j        |j                  S  )r   r\   r   ).0single_cfg_datasetrU   s     rV   
<listcomp>z3KDRecipeDistributed._setup_data.<locals>.<listcomp>  s9       & "#5tGG  rX   )datasetspackedFr   )num_replicasr@   r   r2   )padding_idx
ignore_idx)r   r   sampler
collate_fnz$Dataset and Sampler are initialized.)r   r   r   r   r   r\   r   rD   r   r?   r@   r   r   r   pad_idr   r   r   r   r   r   )	rU   r   r   r   r  dsr  r
  
dataloaders	   `        rV   r   zKDRecipeDistributed._setup_data~  s7    k:.. 		6   *5  H 111BR511FF#KAAB __Xu55F$
 
 
  ! & $ 6#}9    ) 
 
 

" 	C!GHHH
""rX   epochc                 v   i }|dz   | j         k     }t          j        | j        | j        | j                  }|r-t          j        | j        | j        | j        | j                  }nd}| j        rIt          |          }|	                    t          j
        |i           t          || j        | j                  }|	                    t          j        |i           |re|	                    t          j        |t          j        | j        t          j        | j        t          j        | j         t          j        | j        i           | j        | j        t/          | j        | j        | j                  dd}|	                    t          j        |i           | j                            |||| j                   dS dS )a  
        Checkpoint the state of the recipe. The constructed checkpoint state dict
        contains the following information:
        - Merged weights with key MODEL_KEY
        - Adapter weights with key ADAPTER_KEY
        - Relevant recipe state if training is not complete
        - If the `self._save_adapter_weights_only` option is True, the checkpointer will save only the adapter weights

        To correctly resume from training, the adapter weights and recipe state must be provided along with the base model weights.
        r/   r,   N)r@   alphaLORA)rr   target_modules	peft_type)r  intermediate_checkpointadapter_only)rL   r   gather_cpu_state_dictr   rA   r7   get_full_optimizer_state_dictr   r   updater_   r   r   r   r   r   rj   r2   ri   rJ   rl   rk   rM   r   r   r   r   ADAPTER_CONFIGr]   save_checkpointrQ   )	rU   r  ra   r  cpu_state_dictr{   adapter_state_dictmerged_state_dictadapter_configs	            rV   r  z#KDRecipeDistributed.save_checkpoint  s    "'!)d.?"? "7K<
 
 
 # 	"%C"|	  NN "N  ,	 "8!G!G""H$8:L#MNNN !5_&! ! !
 ""H$68I#JKKK ' 	&& (. )49 +T_ 143D .0H   _"."7++.# #
 $	 	N ""H$;^#LMMM..(?!<	 /     O,	 ,	rX   batchc                    |d         |d         }}|                     dd           }|                     dd           }|                     |||          }t          j        |ddd f         | j        d |j        d                  f          }t          |t                    s>|                    d	          }|                    d	|	                    d	                    }t          j
                    5  |                     |||          }d d d            n# 1 swxY w Y   |                     |||          }|                     ||          }	~~|	|fS )
Ntokenslabelsmask	input_pos)r%  r&  .r/   r   )rD   r   r;   hstackr   shaper   r   reshapesizeno_gradr   r   r   )
rU   r!  r#  r$  r%  r&  logitsteacher_logitsr   r   s
             rV   
_loss_stepzKDRecipeDistributed._loss_step  s    x%/ yy&&IIk400	 V$)DD
 CG_d67Ha7HIJ
 
 &$'' 	9^^B''F^^BB88F ]__ 	Y 	Y!00di0XXN	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y ""6>6BB }}VV,, W}s   3DDDc           	      	   t          j                     | j                                         t	          j                    }d}d}d}| j                                         t          | j	        | j
                  D ][}| j                            |           t          | j        | j        dk               }t!          | j                  D ]\  }}| j        || j        z  | j        k    r n| j        rS|dk    rM| j        rF|| j        | j        z   k    r3| j        j        dk    r#t4          j        j                                         t=          j        || j                   |d         | j         j!        k    "                                }	||	z  }| #                    |          \  }
}||
|	z  z  }|||	z  z  }d| j$        z
  |
z  | j$        |z  z   }|%                                 |dz   | j        z  dk    rKt4          j&        '                    |           t4          j&        '                    |           t4          j&        '                    |           t          j(        | j)        | j*        |z             |+                                |z  }|+                                |z  }| j        ,                                 | j                            d           | j-        ,                                 | xj.        dz  c_.        |
+                                }|+                                }d| j$        z
  |z  | j$        |z  z   }|/                    d           |0                    |dz    d	| j.         d
|            | j.        | j1        z  dk    r| j        rt	          j                    |z
  }|||| j        j2        d         d         ||| j*        z  z  d}| j3        r-|/                    t          j4        | j                             | j5        6                    || j.                   d}d}d}t	          j                    }| j        rM|dk    rG| j        r@|| j        | j        z   | j7        z   k    r%t4          j        j                            d           | j        ,                                 | xj	        dz  c_	        | 8                    |           ]| j        9                                 dS )z)
        The core training loop.
        r   )totaldisableNcudar$  r/   T)set_to_none|z|Loss: lr)r   
class_lossr   r6  tokens_per_second_per_gpur,   )step)r   )r  ):r   cleanup_before_trainingr   	zero_gradr   r   r   startrangerJ   rL   r   	set_epochr%   r   r@   	enumerater   rM   rS   rA   r   r   r   r7   typer;   r3  memory_record_memory_historyr   batch_to_devicer   r   sumr/  rT   backwardr   
all_reducescale_gradsr   r?   itemr9  r   rN   r  set_descriptionrE   param_groupsrF   r   r   log_dictr   r  stop)rU   t0running_class_lossrunning_kd_loss
num_tokens
curr_epochpbaridxr!  current_num_tokensr7  r   current_lossclass_loss_to_logkd_loss_to_logloss_to_logtime_per_steprK  s                     rV   trainzKDRecipeDistributed.train*  sQ   
 	(*** 	!!###   
1BCC t	3 t	3J M##J///d3$)q.=QRRRD'(899 k& k&
U,8 AA/0 0 E &?"a4 (t7$:TTTT)V33J%<<>>>%eT\:::
 (Ot}'AA#%% # 00
&*ooe&<&<#
G"j3E&EE"7-?#??& !%'!9 : %%''' !Gt@@AEE%00<<<%001CDDD%00AAA (do
6RSSS(:(?(?(A(AJ(N%%4%9%9%;%;j%HNO((***O--$-???&++---$$)$$(2(9(9%%,\\^^NDN*)#*,0N^,K#LK KKNNN((%>RRD,<RR[RR   (4+BBaGG . H )-(9(;(;b(@$/*;'5"&/">q"A$"G9C,t>:@$ $  6 $OO ( 9 N N N   +44$!%!1 5    *+&&'O!"J*,,B &	K"a4 (/01011 1
 J%<<T<JJJ
 ##%%%%OOq OO  z 2222rX   c                 b    | j         r| j                                         t                       d S N)rA   r   closer   )rU   s    rV   cleanupzKDRecipeDistributed.cleanup  s4     	(%%'''rX   r\  r   )r*   N)'r   
__module____qualname____doc__r   rW   r   strr   r^   rd   r`   r   r   r	   r;   r   profiler#   r   boolr   r   Moduler   r   r   r   intr   r   r   r   r   r  Tensorr/  rZ  r^  r  rX   rV   r(   r(   +   s       > >@$2J $24 $2 $2 $2 $2L
 tCH~    ,
 tCQTH~    &d38n & & & & &Pq
 q
 q
 q
 q
 q
h 48C C$Z0C	u~%}4	5C C C CX 6:<@w ww *.w 	w
  $w  $CH~w  (S	2w "*$sCx.!9w 
w w w wrRR  (S	2R 	R
  $R sCx.R 
R R R Rj UY '9A$sCx.9Q	   $   	
 
    1#1# 1# 	1#
 
!:-	.1# 1# 1# 1#fOS OT O O O Ob&#u|+,&
,	%& & & &PH H H HT           rX   r(   r)   r*   c                    t          j                    st          d          t          d           |                     dd          rt          j                     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
    zDistributed finetune recipe should be run via a distributed launcher.If using tune CLI, please specify --nnodes 1 and --nproc_per_node [num_gpus]zcuda:nccl,cpu:gloorq   Fr(   )recipe_namer)   )r)   N)r   is_distributedRuntimeErrorr   rD   set_torch_num_threadsr   r   r(   r   rZ  r^  )r)   recipes     rV   recipe_mainrn    s     "$$ 
[
 
 	
 +,,,
ww!5)) ) 	&(((
"7SAAAA S)))F
LLSL
LLNNN
NNrX   __main__):sysr   	functoolsr   typingr   r   r   r   r   r	   warningsr
   r;   	omegaconfr   r   r   torch.distributedr   r   torch.optimr   torch.utils.datar   r   	torchtuner   r   r   r   torchtune.datar   r   torchtune.datasetsr   torchtune.modules.peftr   r   r   r   r   r   r    r!   torchtune.recipe_interfacesr"   torchtune.trainingr#   r$   r%   
get_loggerr   r(   parsern  r   exitr  rX   rV   <module>r     s{   


        : : : : : : : : : : : : : : : :        , , , , , , , ,       G G G G G G G G ! ! ! ! ! ! ; ; ; ; ; ; ; ; 6 6 6 6 6 6 6 6 6 6 6 6 D D D D D D D D , , , , , ,	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 : 9 9 9 9 9 : : : : : : : :      ewL  L  L  L  L + L  L  L ^ Z D    6 zCH[[]] rX   