
    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	 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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,m-Z- d dl.m/Z/ d dl0m0Z0  ej1        d          Z2 G d de/          Z3ej4        deddfd            Z5e6dk    r e j7         e5                       dS dS )    N)partial)AnyDictListOptionalTuple)warn)
DictConfig
ListConfig)nn)destroy_process_groupinit_process_group)	Optimizer)
DataLoaderDistributedSampler)configmodulesrlhftrainingutils)CROSS_ENTROPY_IGNORE_IDXpadded_collate_dpo)ConcatDataset)	disable_adapter
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)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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'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j        d"eej        ej        f         deej        ej        ej        ej        f         fd#Zd(d$Zd(d%ZdS ))LoRADPORecipeDistributeda  
    Distributed LoRA DPO recipe for dense transformer-based LLMs such as Llama2. This recipe supports
    distributed training and can be run on a single node (1 to 8 GPUs). This is based on HF's DPOTrainer
    in the TRL library: https://github.com/huggingface/trl/blob/main/trl/trainer/dpo_trainer.py#L65

    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.

        - 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 * number of GPUs * gradient accumulation steps.

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

            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.

    The following losses are supported in this recipe:
        - :class:`~torchtune.rlhf.loss.DPOLoss`: Direct Preference Optimization (DPO).
        - :class:`~torchtune.rlhf.loss.RSOPLoss`: Rejection Sampling Optimization (RSO).

    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.
        ValueError: If world_size is 1
        RuntimeError: If ``dtype`` is set to bf16 and the hardware does not support bf16.
        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                 l   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        r1| j        j        dk    r!t*                              d	           d| _        |                    d
d          | _        |                    dd          | _        | j        r6| j        j        dk    rt3          d          | j        st3          d          n!| j        rt          j        t*          d           t	          j        |j        |                    dd                     | _        d| _        |j        | _        |j         | _         d| _!        |j"        | _#        |                    dd          | _$        |j%        | _&        d S )NdevicezVfull fp16 training is not supported with this recipe. Please use bf16 or fp32 instead.r   log_every_n_steps   log_peak_memory_statsFcudazplog_peak_memory_stats was set to True, however, training does not use cuda. Setting log_peak_memory_stats=False.enable_activation_checkpointingenable_activation_offloadingzFenable_activation_offloading should only be True when training on CUDAz]enable_activation_offloading should only be True when enable_activation_checkpointing is TruezHint: enable_activation_checkpointing is True, but enable_activation_offloading isn't. Enabling activation offloading should reduce memory further.cudnn_deterministic_mode)seed
debug_modesave_adapter_weights_only)'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typeloginfo _enable_activation_checkpointing_enable_activation_offloadingRuntimeErrorlog_rank_zeroset_seedr4   
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)selfr(   s     p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/recipes/lora_dpo_distributed.py__init__z!LoRADPORecipeDistributed.__init__~   sA   'sz:::(4<HHH;%-''h   &+%B%D%D"!Y!^ >"%''*=q"A"A&)gg.Eu&M&M#& 	04<+<+F+FHH C   +0D' 14-u1
 1
- .1WW*E.
 .
* - 	| F**"\   8 "s   2 	O   %cgg.H$&O&O
 
 
	 J#&#: '*'A$*-''2Mu*U*U',/,K)))    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   instantiaterV   _checkpointerload_checkpointr   ADAPTER_KEYr>   _update_recipe_state)rZ   r^   checkpoint_dicts      r[   rc   z(LoRADPORecipeDistributed.load_checkpoint   s     $/%)%A
 
 
 ,<<>>
 ' 	7#?:: f  
 %%o666r]   	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_KEYrP   r4   SEED_KEYr	   rS   MAX_STEPS_KEYrR   TOTAL_EPOCHS_KEYKeyError)rZ   rg   es      r[   re   z-LoRADPORecipeDistributed._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                            |           t          j        t          d           | 	                    |j
                  }|                     |j        |j        | j        |                    dd          |                    dd          |                    dd          |t           j                 | j        r|t           j                 nd	          | _        t          j        |j                  | _        |                     |j        | j        r|t           j                 nd
          | _        t          j        |j                  | _        t          j        t          d           |                     |j        |j        |j                   \  | _!        | _"        tG          | j"                  | j$        z  | _%        | j&        | j&        | j%        k     r| j&        | _%        | j'        | j%        z  | _(        | )                    |j*        | j+        | j%        z  | j(        dz
            | _,        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.
        zmetric logger is initialized.)r^   custom_sharded_layersNfsdp_cpu_offloadFfsdp_reshard_after_forwardT)	cfg_modelr1   r2   rq   rr   reshard_after_forwardbase_model_state_dictlora_weights_state_dict)cfg_optimizeropt_state_dictzLoss is initialized.)cfg_datasetshuffle
batch_sizer.   )cfg_lr_schedulernum_training_steps
last_epoch)-rB   r   ra   metric_logger_metric_logger
log_configr   rN   rI   rc   checkpointer_setup_modelmodelr1   rL   rE   r   	MODEL_KEYrV   rd   _model	tokenizer
_tokenizer_setup_optimizer	optimizerOPT_KEY
_optimizerloss_loss_fn_setup_datadatasetr{   r|   _sampler_dataloaderlenrY   _steps_per_epochrS   rP   rT   _setup_lr_schedulerlr_schedulerrR   _lr_scheduler)rZ   r(   rf   s      r[   setupzLoRADPORecipeDistributed.setup   sF   
  	0"("4S5F"G"GD **3///C!@AAA..@P.QQ''i,/,O)-)K"%''*A4"H"H WW%7??"%''*F"M"M"1(2D"E / 455 ( 
 
 !,S];;//- / 011 0 
 
 *3844C!7888 +/*:*:K~ +; +
 +
't'  !!T%FF 	 $0(4+@@@$($<D!?T-BB "55 -#043HH'!+ 6 
 
r]   rt   r1   r2   rr   ru   rv   rq   rw   c	           	         |j         | _        |j        | _        t	          |j                  | _        |j        | _        t          |dd          | _
        t          j                    }	t          j        t          d           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                   |r!t!          j        |
t6          j        h           t;          t           j        |          g}t!          j        |
|||           |r!t!          j         |
|| j!        |	          \  }}nd
\  }}t!          j        | j                  5  | j!        5  |rdn| j!        }|
                                D ]|}tE          |tF                    stE          |tH                    r,|s*|%                    |           |&                                 tO          |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 ](}tO          |d          rd}|)                                 )|r;|
                                D ]&}tO          |d          r|)                                 'tU          | j        | j        | j
        ||||           t!          j+        |
|          | _,        t!          j-        |
           t          j        t          dt          j                    |	z
  dd           | j.        r.t!          j/        | j!                  }t!          j0        |           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 ...metaN)auto_wrap_policy)names_to_match)r   shard_conditionscpu_offloadru   )r   NNcpur+   	rope_initinitialize_dora_magnitudeT)lora_attn_modulesapply_lora_to_mlpr   base_missingbase_unexpectedlora_missinglora_unexpectedz0Instantiating model and loading checkpoint took z.2fz secs)3	lora_rank
_lora_rank
lora_alpha_lora_alphalistr   _lora_attn_modulesr   _apply_lora_to_mlpgetattr_apply_lora_to_outputtimeperf_counterr   rN   rI   r   set_default_dtyper;   r<   r,   r   ra   r   adapter_paramsr!   set_activation_checkpointingr   TransformerSelfAttentionLayerr   get_shard_conditionsshard_modelload_from_full_model_state_dictr8   
isinstancer    r   to_emptyinitialize_parametershasattrr   r   r"   get_act_offloading_ctx_manageractivations_handling_ctx!validate_no_params_on_meta_devicerB   get_memory_statslog_memory_statsdistributedbarrier)rZ   rt   r1   r2   rr   ru   rv   rq   rw   
init_startr   fsdp_shard_conditionsr   r   lora_devicemr   r   is_doramemory_statss                       r[   r   z%LoRADPORecipeDistributed._setup_modelH  sA   & $-$/"&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* 	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 .++--- 	2]]__ 2 219:: 2//1110"5"5!%!;%+%+	
 	
 	
 	
 )1(O/)
 )
% 	25999jt?P?R?RU_?_jjjj	
 	
 	
  	4#4DLIIIL%l333 	!!###sm   C'/CC'C	C'C	C''C+.C+3I<;BI%I<%I)	)I<,I)	-I<<J J rx   ry   c                     t          j        || j                                                  }|r!t	          j        | j        ||| j                   t          j        t          d           |S )Nz#Optimizer and loss are initialized.)
r   ra   r   
parametersr   #load_from_full_optimizer_state_dictr8   r   rN   rI   )rZ   rx   ry   r   s       r[   r   z)LoRADPORecipeDistributed._setup_optimizer  sm     &}dk6L6L6N6NOO	 	8	   	C!FGGGr]   r}   r~   r   c                 t    t          j        || j        ||          }t          j        t
          d           |S )N)r~   r   z'Learning rate scheduler is initialized.)r   ra   r   r   rN   rI   )rZ   r}   r~   r   r   s        r[   r   z,LoRADPORecipeDistributed._setup_lr_scheduler  sE     )O1!	
 
 
 	C!JKKKr]   rz   r{   r|   c                     t          |t                    r fd|D             }t          |          }nt          j        | j                  }t          | j         j        |d          }t          |||dt          t           j        j        t                              }t          j        t           d	           ||fS )
z
        All data related setup happens here. Currently this recipe only supports the
        DistributedSamplers with Map-style Datasets which fit into memory. Other samplers,
        iterable datasets and streaming datasets are not supported.
        c                 F    g | ]}t          j        |j                   S )r   )r   ra   r   ).0single_cfg_datasetrZ   s     r[   
<listcomp>z8LoRADPORecipeDistributed._setup_data.<locals>.<listcomp>  s<       & "#5QQQ  r]   )datasetsr   r   )num_replicasrA   r{   r4   T)padding_idx
ignore_idx)r   r|   sampler	drop_last
collate_fnz$Dataset and Sampler are initialized.)r   r   r   r   ra   r   r   r@   rA   r   r   r   pad_idr   r   rN   rI   )rZ   rz   r{   r|   r   dsr   
dataloaders   `       r[   r   z$LoRADPORecipeDistributed._setup_data  s     k:.. 	L   *5  H 111BB#K4?KKKB$T_49gTU
 
 
  !" O23  
 
 

 	C!GHHH
""r]   epochc                    i }|dz   | j         k     }t          j        | j        | j        | j        | j                  }|r-t          j        | j        | j        | j        | j                  }nd}| j        rS| j        r|}nLt          |          }t          || j        | j                  }|                    t          j        |i           |                    t          j        |i           |re|                    t          j        |t          j        | j        t          j        | j        t          j        | j         t          j        | j        i           | j        | j        t1          | 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

        Checkpointer will save the merged weights, adapter weights and recipe state in
        different checkpoint files. To correctly resume from training, the adapter weights
        and recipe state must be provided along with the base model weights.r.   )r,   adapter_weights_onlyr+   N)rA   alphaLORA)rr   target_modules	peft_type)r   intermediate_checkpointadapter_only)rR   r   gather_cpu_state_dictr   rB   r8   rW   get_full_optimizer_state_dictr   r   r   r   r   updater   rd   r   rk   r4   rj   rP   rm   rl   rS   r   r   r   r   ADAPTER_CONFIGrb   save_checkpoint)	rZ   r   rf   r   cpu_state_dictry   adapter_state_dictmerged_state_dictadapter_configs	            r[   r   z(LoRADPORecipeDistributed.save_checkpoint  s     "'!)d.?"? "7K<!%!@	
 
 
 # 	"%C"|	  NN "N  .	. P%3"" &<N%K%K" %9"*% % %!
  &&(:<M'NOOO""H$8:L#MNNN ' 	&& (. )49 +T_ 143D .0H   _"."7++.# #
 $	 	N ""H$;^#LMMM..(?!<	 /     S.	 .	r]   r   batchc                 n   |\  }}|                     | j                  }|                     | j                  }|j        d         dz  }| j        5   ||          }ddd           n# 1 swxY w Y   t	          j        ||          }|d|         }||d         }	|d|         }
||d         }||	|
|fS )az  
        Run forward pass of the model with chosen and rejected samples concatenated.

        Args:
            model (nn.Module): The model to be used for the forward pass.
            batch (Tuple[torch.Tensor, torch.Tensor]): Tuple of input_ids and labels.

        Returns:
            Tuple of chosen log probs, rejected log probs, chosen logits, rejected logits.
        r      N)tor8   shaper   r   get_batch_log_probs)rZ   r   r   concatenated_input_idsconcatenated_labels
len_chosen
all_logitsall_log_probschosen_log_probsrejected_log_probschosen_logitsrejected_logitss               r[   concatenated_forwardz-LoRADPORecipeDistributed.concatenated_forwardg  s    7<3 3!7!:!:4<!H!H144T\BB ,1!49
* 	7 	7566J	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 0=PQQ(*5*:;;7";J;/$Z[[1 "4m_UUs   A))A-0A-c                    t          j                     | j                                         t	          j                    }d}dddddddd}d}t          | j        | j                  D ]}| j	        
                    |           t          | j        | j        dk               }t          | j                  D ]\  }}| j        || j        z  | j        k    r nk|t%          j        |d                                                   z  }|                     | j        |          \  }	}
}}|                                                                }|                                                                }~~t%          j                    5  t5          | j                  5  |                     | j        |          \  }}}}ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |                     |	|
||          \  }}}||k                                    }|                                }|| j        z  }||z  }d| j        z  }|dxx         ||                                z  z  cc<   |dxx         ||                                z  z  cc<   |dxx         ||                                z  z  cc<   |d	xx         ||	                                                                z  z  cc<   |d
xx         ||
                                                                z  z  cc<   |dxx         ||z  z  cc<   |dxx         ||z  z  cc<   |                                 |dz   | j        z  dk    rt$          j                            |           t$          j                            |           |D ]=}t$          j                            ||         t$          j        j         j!                   >| j        "                                 | j                            d           | j#        "                                 | xj$        dz  c_$        |%                                }|&                    d           |'                    |dz    d| j$         d|            | j$        | j(        z  dk    rk| j)        rct	          j                    |z
  }|| j        j*        d         d         ||| j+        z  z  |d         ,                                |d         ,                                |d         ,                                |d         |d         z
  ,                                |d	         ,                                |d
         ,                                |d         ,                                |d         ,                                d}| j-        r-|&                    t          j.        | j/                             | j0        1                    || j$                   d}d |D             }d}t	          j                    }| xj        dz  c_        | 2                    |           dS )z)
        The core training loop.
        r   )rewards/chosenrewards/rejectedrewards/accuracieslog_probs/chosenlog_probs/rejectedlogits/chosenlogits/rejected)totaldisableNr.   r  r  r  r	  r
  r  r  )opT)set_to_none|z|Loss: lr)r   r  tokens_per_second_per_gpur  r  r  zrewards/marginsr	  r
  r  r  r+   )stepc                     i | ]}|d S )r    )r   keys     r[   
<dictcomp>z2LoRADPORecipeDistributed.train.<locals>.<dictcomp>4  s    &I&I&I#sA&I&I&Ir]   )r   )3r   cleanup_before_trainingr   	zero_gradr   r   rangerP   rR   r   	set_epochr$   r   rA   	enumerater   rS   rY   r<   tensornumelr  r   detachmeanno_gradr   r   floatbackwardr   
all_reduceReduceOpAVGr  r   rT   itemr   set_descriptionrF   rB   param_groupsr@   r   rG   r   r8   r   log_dictr   )rZ   t0running_lossrunning_metrics
num_tokens
curr_epochpbaridxr   policy_chosen_log_probspolicy_rejected_log_probspolicy_chosen_logitspolicy_rejected_logitspolicy_chosen_logits_meanpolicy_rejected_logits_meanreference_chosen_log_probsreference_rejected_log_probs_r   chosen_rewardsrejected_rewardsreward_accuraciesscaling_factorr  loss_to_logtime_per_stepr+  s                              r[   trainzLoRADPORecipeDistributed.train  s   
 	(*** 	!!###     !"# !"# 
 
 
  1BCC W	3 W	3J M##J///d3$)q.=QRRRD'(899 M- M-
U,8 AA/0 0 E el58>>+;+;<<<
 --dk5AA+-(* -A,G,G,I,I,N,N,P,P).D.K.K.M.M.R.R.T.T+ )*@]__ F Fodk&B&B F F 11$+uEE24F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F :>+-.0	: :6n&6 &46F%F$M$M$O$O!yy{{d?? $99    0111"^%8%8%:%::111   2333"%5%:%:%<%<<333   4555"%6%;%;%=%==555   2333"%<%C%C%E%E%J%J%L%LL333   4555"%>%E%E%G%G%L%L%N%NN555  000"%>>000   1222"%@@222  !Gt@@AEE%00>>>%00<<<.  )44+C0U5F5O5S 5     O((***O--$-???&++--- $$)$$"."3"3"5"5KKKNNN((%>RRD,<RR[RR   (4+BBaGG . H )-(9(;(;b(@$/"&/">q"A$"G9C,t>:@.=>N.O.S.S.U.U0? 21!cee2A 43!cee /0@ A"12D"E!F!cee0? 21!cee2A 43!cee-<_-M-Q-Q-S-S/>?P/Q/U/U/W/W/$ $2  6 $OO ( 9 N N N   +44$!%!1 5    $%L&I&I&I&I&IO!"J*,,BOOq OO  z 2222oW	3 W	3s6   G%!!G	G%GG%GG%%G),G)c                 b    | j         r| j                                         t                       d S N)rB   r   closer   )rZ   s    r[   cleanupz LoRADPORecipeDistributed.cleanup<  s4     	(%%'''r]   r   rD  )r)   N) __name__
__module____qualname____doc__r
   r\   r   strr   rc   re   r   boolr   r   r   Moduler   r   r   intr   r   r   r   r   r   r<   Tensorr  rB  rF  r  r]   r[   r'   r'   )   s       R Rh:LJ :L4 :L :L :L :Lx
 tCH~    2&d38n & & & & &PK
 K
 K
 K
 K
 K
j 6:<@} }} *.} '+	}
 }  $}  $CH~}  (S	2} "*$sCx.!9} 
} } } }@ UY '9A$sCx.9Q	   $   	
 
    (#(# (# 	(#
 
!:-	.(# (# (# (#TUU 
U U U UnVYV',U\5<-G'HV	u|U\5<E	FV V V VBr3 r3 r3 r3h           r]   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:gloorr   Fr'   )recipe_namer(   )r(   N)r   is_distributedrM   r   rE   set_torch_num_threadsr   r   r'   r   rB  rF  )r(   recipes     r[   recipe_mainrU  B  s     "$$ 
[
 
 	
 +,,,
ww!5)) ) 	&(((
"<#FFFF%#...F
LLSL
LLNNN
NNr]   __main__)8sysr   	functoolsr   typingr   r   r   r   r   warningsr	   r<   	omegaconfr
   r   r   torch.distributedr   r   torch.optimr   torch.utils.datar   r   	torchtuner   r   r   r   r   torchtune.datar   r   torchtune.datasetsr   torchtune.modules.peftr   r   r   r   r   r   r    r!   r"   torchtune.recipe_interfacesr#   r$   
get_loggerrI   r'   parserU  rG  exitr  r]   r[   <module>rg     sm   


        3 3 3 3 3 3 3 3 3 3 3 3 3 3        , , , , , , , ,       G G G G G G G G ! ! ! ! ! ! ; ; ; ; ; ; ; ; < < < < < < < < < < < < < < G G G G G G G G , , , , , ,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 : 9 9 9 9 9      ewV  V  V  V  V 0 V  V  V r Z D    6 zCH[[]] r]   