
    Pijg                        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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' 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/e0dk    r e j1         e/                       dS dS )    N)partial)AnyDictOptionalTuple)warn)
DictConfig
ListConfig)nn)	Optimizer)
DataLoaderDistributedSampler)configmodulesrlhftrainingutils)CROSS_ENTROPY_IGNORE_IDXpadded_collate_dpo)ConcatDataset)disable_adapterget_adapter_paramsget_adapter_state_dictget_lora_module_namesget_merged_lora_ckpt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eef         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e         dedede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 )&LoRADPORecipeSingleDevicead  
    LoRA DPO recipe for dense transformer-based LLMs such as Llama2 for
    single device training. This is based on HF's DPOTrainer in the
    TRL library: https://github.com/huggingface/trl/blob/main/trl/trainer/dpo_trainer.py#L65

    This recipe supports:
        - Activation checkpointing. This is enabled by default but is configurable.
        - Activation offloading - this is enabled by default and should only be used alongside
            activation checkpointing.
        - Full bf16 training for supported HW architectures. We currently check bf16 support via
            the `torch.cuda.is_bf16_supported` API. This is disabled by default but can be enabled via
            setting `dtype=bf16` in configuration.
        - Checkpointing: of LoRA adapter parameters and their optimizer states. When resuming
            from a checkpoint, the adapter parameters are loaded from the checkpoint along
            with the base model weights. Note that intra-epoch resumption is not supported.
        - Logging to terminal, WandB, or TensorBoard.


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

    Assumptions:
        - Checkpoints are ONLY saved at epoch boundaries. In case of failure, work done
            in ongoing epoch is lost.
        - Datasets are Map-style and data fits in memory (not streamed).

    The following configs can be used to run this recipe:
        >>> tune ls
        RECIPE                          CONFIG
        lora_dpo_single_device          llama2/7B_lora_dpo_single_device

    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 ``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| _        |                    d	d          | _        |                    d
d          | _        | j        r6| j        j        dk    rt+          d          | j        st+          d          n!| j        rt          j        t"          d           t	          j        |j        |                    dd                     | _        d| _        |j        | _        |j        | _        d| _        |j        | _        |                    dd          | _         |j!        | _"        d S )NdevicezHfp16 precision is not supported in this recipe. Please use fp32 or bf16.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.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 TruezHint: enable_activation_checkpointing is True, but enable_activation_offloading isn't. Enabling activation offloading should reduce memory further.cudnn_deterministic_mode)seed
debug_moder   save_adapter_weights_only)#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 _enable_activation_checkpointing_enable_activation_offloadingRuntimeErrorlog_rank_zeroset_seedr0   
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     r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/recipes/lora_dpo_single_device.py__init__z"LoRADPORecipeSingleDevice.__init__S   s   'sz:::(4<HHH ;%-''Z  
 >"%''*=q"A"A&)gg.Eu&M&M#& 	04<+<+E+EHHy   +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   instantiaterN   _checkpointerload_checkpointr   ADAPTER_KEYr:   _update_recipe_state)rR   rV   checkpoint_dicts      rS   r[   z)LoRADPORecipeSingleDevice.load_checkpoint   s     $/%)%A
 
 
 ,<<>>' 	7#?:: f  
 %%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_KEYrH   r0   SEED_KEYr   rK   MAX_STEPS_KEYrJ   TOTAL_EPOCHS_KEYKeyError)rR   r_   es      rS   r]   z.LoRADPORecipeSingleDevice._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           	      v   t          j        |j                  | _        | j                            |           |j        | _        |                     |j                  }| 	                    |j
        |j        | j        |j        |t          j                 | j        r|t          j                 nd          | _        t          j        |j                  | _        t(                              d           |                     |j        | j        r|t          j                 nd          | _        t          j        |j                  | _        t(                              d           |                     |j        |j        |j                  \  | _         | _!        tE          | j!                  | j#        z  | _$        | j%        0| j%        | j$        k     r | j%        | _$        | j&        | j$        z  | _'        | (                    |)                    dd          | 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.
        )rV   N)	cfg_modelr,   r-   compile_modelbase_model_state_dictlora_weights_state_dictz#Tokenizer is initialized from file.)cfg_optimizeropt_state_dictzLoss function is initialized.)cfg_datasetshuffle
batch_sizelr_schedulerr)   )cfg_lr_schedulernum_training_steps
last_epoch),r   rY   metric_logger_metric_logger
log_configcompile_model_compiler[   checkpointer_setup_modelmodelr,   rD   r   	MODEL_KEYrN   r\   _model	tokenizer
_tokenizerrA   rB   _setup_optimizer	optimizerOPT_KEY
_optimizerloss_loss_fn_setup_datadatasetrp   rq   _sampler_dataloaderlenrQ   _steps_per_epochrK   rH   rL   _setup_lr_schedulerr=   rJ   _lr_scheduler)rR   r#   r^   s      rS   setupzLoRADPORecipeSingleDevice.setup   s   
 %01BCC 	&&s+++!k..@P.QQ''i,/,O)-)K+"1(2D"E / 455 ( 
 
 !,S];;6777//- / 011 0 
 
 *38440111 +/*:*:K~ +; +
 +
't'  !!T%FF 	 $0(4+@@@$($<D!#1FFD "55 WW^T::#043HH'!+ 6 
 
rU   ri   r,   r-   rj   rk   rl   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   |j        | _        |j        | _	        t          |j                  | _        |j        | _        t          |dd          | _        t#          |          | _        t'          || j                   |r!t          j        |t*          j        h           |                    |d          \  }}	|r|                    |d          \  }
}nd\  }
}t1          | j        | j        | j        ||	|
|           t          j        ||          | _        t6                              d| j         d           |rt          j        |           | j        j        d	k    r.t          j        | j        
          }t          j         |           |S )Napply_lora_to_outputF)auto_wrap_policy)strict)NN)lora_attn_modulesapply_lora_to_mlpr   base_missingbase_unexpectedlora_missinglora_unexpectedz$Model is initialized with precision .r+   r&   )!r   set_default_dtyper7   r4   r   rY   	lora_rank
_lora_rank
lora_alpha_lora_alphalistr   _lora_attn_modulesr   _apply_lora_to_mlpgetattr_apply_lora_to_outputr   adapter_paramsr   set_activation_checkpointingr   TransformerSelfAttentionLayerload_state_dictr   get_act_offloading_ctx_manageractivations_handling_ctxrA   rB   rj   r@   get_memory_statslog_memory_stats)rR   ri   r,   r-   rj   rk   rl   r}   r   r   r   r   memory_statss                rS   r|   z&LoRADPORecipeSingleDevice._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#-$/"&y'B"C"C"+"=%,Y8NPU%V%V"077UD$7888* 	1)N(O    ).(=(=!% )> )
 )
%o # 	7,1,A,A' -B - -)L// -7)L/0"5"5!%!;%+%+	
 	
 	
 	
 )1(O/)
 )
% 	FFFFGGG  	*"5)))<%%#4DLIIIL%l333s3   AAAA	A
A	AA!Arm   rn   c                     t          j        || j                                                  }|r|                    |           t
                              d           |S )Nz#Optimizer and loss are initialized.)r   rY   r   
parametersr   rA   rB   )rR   rm   rn   r   s       rS   r   z*LoRADPORecipeSingleDevice._setup_optimizerQ  sY     &}dk6L6L6N6NOO	 	6%%n5556777rU   rs   rt   ru   c                     |t                               d           d S t          j        || j        ||          }t                               d           |S )NzDNo learning rate scheduler configured. Using constant learning rate.)rt   ru   z'Learning rate scheduler is initialized.)rA   rB   r   rY   r   )rR   rs   rt   ru   rr   s        rS   r   z-LoRADPORecipeSingleDevice._setup_lr_scheduler[  sj     #HHV   4)O1!	
 
 
 	:;;;rU   ro   rp   rq   c                 v    t          |t                    r fd|D             }t          |          }nt          j        | j                  }t          |dd|d          }t          |||dt          t           j        j
        t                    	          }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                 F    g | ]}t          j        |j                   S )r   )r   rY   r   ).0single_cfg_datasetrR   s     rS   
<listcomp>z9LoRADPORecipeSingleDevice._setup_data.<locals>.<listcomp>}  s<       & "#5QQQ  rU   )datasetsr   r)   r   )num_replicasrankrp   r0   T)padding_idx
ignore_idx)r   samplerrq   	drop_last
collate_fnz$Dataset and Sampler are initialized.)
isinstancer
   r   r   rY   r   r   r   r   r   pad_idr   rA   rB   )rR   ro   rp   rq   r   dsr   
dataloaders   `       rS   r   z%LoRADPORecipeSingleDevice._setup_dataq  s     k:.. 	L   *5  H 111BB#K4?KKKB$
 
 
  !" O23  
 
 

 	7888
""rU   epochc                    i }|dz   | j         k     }|r||                    t          j        | j                                        t          j        | j        t          j        | j	        t          j
        | j         t          j        | j        i           t          | j                                                  }|                    t          j        |i           | j        srd | j                                                                        D             }t%          || j        | j                  }|                    t          j        |i           | j        | j        t-          | j        | j        | j                  dd}|                    t          j        |i           | j                            |||| j                   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)   c                 >    i | ]\  }}||                                 S  )r+   )r   kvs      rS   
<dictcomp>z=LoRADPORecipeSingleDevice.save_checkpoint.<locals>.<dictcomp>  s&    RRRA!QUUWWRRRrU   )r   alphaLORA)rr   target_modules	peft_type)r   intermediate_checkpointadapter_onlyN)rJ   updater   r   r   
state_dictrc   r0   rb   rH   re   rd   rK   r   r   r\   rO   itemsr   r   r   r~   r   r   r   r   ADAPTER_CONFIGrZ   save_checkpoint)rR   r   r_   r   adapter_state_dictr   merged_state_dictadapter_configs           rS   r   z)LoRADPORecipeSingleDevice.save_checkpoint  s    	"'!)d.?"?" 		$do&@&@&B&B%ty'-t/@*D,D   4DK4J4J4L4LMM(.0BCDDD. 	F SR1G1G1I1I1O1O1Q1QRRRJ 4_&! ! ! h02CDEEE *3''* 
  	
 	
 	(1>BCCC**$;8	 	+ 	
 	
 	
 	
 	
rU   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)tor4   shaper   r   get_batch_log_probs)rR   r}   r   concatenated_input_idsconcatenated_labels
len_chosen
all_logitsall_log_probschosen_log_probsrejected_log_probschosen_logitsrejected_logitss               rS   concatenated_forwardz.LoRADPORecipeSingleDevice.concatenated_forward  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                 	   | j         rt                              d           t          j                    }d}d}t          | j        | j                  D ]}| j        	                    |           t          | j                  }t          | j                  D ]4\  }}| j        || j        z  | j        k    r n||d                                         z  }|                     | j        |          \  }}	}
}|
                                                                }|                                                                }~
~t+          j                    5  t/          | 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z   | j        z  dk    r| j                                         | j                            d           | j        | j                                         | xj        dz  c_        |                                 }|!                    d           |"                    |dz    d| j         d	|            | j        | j#        z  dk    rt          j                    |z
  }|| j        j$        d         d
         ||z  |                                %                                |                                %                                |                                %                                ||z
                                  %                                |	                                                                %                                |                                                                %                                |%                                |%                                d}| j&        r-|!                    tO          j(        | j)                             | j*        +                    || j                   d}d}t          j                    }6| xj        dz  c_        | ,                    |           dS )z)
        The core training loop.
        zpNOTE: torch.compile is enabled and model is compiled in first forward. Expect a relatively slow first iteration.r   )totalNr)   T)set_to_none|z|Loss: lr)r   r   tokens_per_second_per_gpuzrewards/chosenzrewards/rejectedzrewards/accuracieszrewards/marginszlog_probs/rejectedzlog_probs/chosenzlogits/rejectedzlogits/chosenr&   )step)r   )-rz   rA   rB   timeperf_counterrangerH   rJ   r   	set_epochr   r   	enumerater   rK   rQ   numelr   r   detachmeanr8   no_gradr   r   floatbackwardr   r   	zero_gradr   rL   itemr   set_descriptionr>   param_groupsr+   r?   r   r   r4   rw   log_dictr   )rR   t0running_loss
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loss_to_logtime_per_stepr   s                           rS   trainzLoRADPORecipeSingleDevice.train  s     	HH C  
   
  1BCC f	3 f	3J M##J///d3444D'(899 ^- ^-
U,8 AA/0 0 E eAhnn...
 --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 yy{{%36F%F$M$M$O$O!d??$ !Gt@@AEEO((***O--$-???)5*//111$$)$$"."3"3"5"5KKKNNN((%>RRD,<RR[RR  
 '$*AAQFF(,(9(;(;b(@$/"&/">q"A$"G9Cm9S.<.A.A.C.C.G.G.I.I0@0E0E0G0G0K0K0M0M2C2H2H2J2J2N2N2P2P0>AQ0Q!TVV SUU2K2R2R2T2T!TVV SUU0G0N0N0P0P!TVV SUU/J/N/N/P/P-F-J-J-L-L#$ $&  6 $OO ( 9 N N N   +44$!%!1 5    $%L!"J*,,BOOq OO  z 2222Mf	3 f	3s6   F3/!F	F3F  F3#F $F33F7:F7c                 8    | j                                          d S N)rw   close)rR   s    rS   cleanupz!LoRADPORecipeSingleDevice.cleanupq  s    !!#####rU   r  )r$   N)__name__
__module____qualname____doc__r	   rT   r   strr   r[   r]   r   boolr   r   Moduler|   r   r   intr   r   r   r   r   r   r8   Tensorr   r  r  r   rU   rS   r"   r"   '   s       ) )V:LJ :L4 :L :L :L :Lx
 tCH~    ,&d38n & & & & &PH
 H
 H
 H
 H
 H
b =A8 88 *.8 '+	8
 8  $CH~8 "*$sCx.!98 
8 8 8 8v UY '9A$sCx.9Q	   ":.   	
 
)	   ,)#)# )# 	)#
 
!:-	.)# )# )# )#V;
S ;
T ;
 ;
 ;
 ;
zVYV',U\5<-G'HV	u|U\5<E	FV V V VBu3 u3 u3 u3n$ $ $ $ $ $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   rx   r"   r   r  r  )r#   recipes     rS   recipe_mainr&  u  sb     "=3GGGG&3///F
LLSL
LLNNN
NNrU   __main__)2sysr   	functoolsr   typingr   r   r   r   warningsr   r8   	omegaconfr	   r
   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   torchtune.recipe_interfacesr   r   
get_loggerrA   r"   parser&  r  exitr   rU   rS   <module>r7     s;   


        - - - - - - - - - - - -        , , , , , , , ,       ! ! ! ! ! ! ; ; ; ; ; ; ; ; < < < < < < < < < < < < < < G G G G G G G G , , , , , ,                  : 9 9 9 9 9      ewK	$ K	$ K	$ K	$ K	$ 1 K	$ K	$ K	$\ Z D     zCH[[]] rU   