
    Y:iI              
          S r SSKJr  SSKrSSKJr  SSKJr  SSKJrJ	r	J
r
JrJrJrJrJr  SSKJrJrJrJrJrJrJrJrJ
r
JrJrJrJrJrJrJrJrJrJ r JrJ!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/JrJ0r0J1r1J2r2J3r3J4r4JrJ
r
JrJrJ,r,J0r0Jr  SSK0r0SSK7  SSK5J6r6J7r7  SS	K8J9r9  SSKrSSK:r;SS
K<J=r=  SSKJr  SSK>J?r?J@rA  SSKBJCrC  SSKDrDSSKEJFrF  S rG SSSSSS.rH\R                  " SS\HS9S 5       rJS\R                  S\KS\KS\R                  4S jrLS\R                  S\R                  S\KS\KS\R                  4
S jrMS\R                  S\KS\R                  4S jrN\6 " S  S!\5      5       rO  " S" S#\5      rP " S$ S%\P5      rQ \R" \,S&5      (       a3  SSK-r- " S' S(\-R                  5      rT \,R                  " \T" S)5      5        gg)*z;
2025.10.10
2025.10.9
4.56.2
0.23.0
__UNSLOTH_VERSIONING__
    )TensorN)
functional)AnyListOptionalTupleUnionDictSetCallable)0r   BaseImageProcessorr   DataCollatorDatasetEvalPredictionFeatureExtractionMixinFrozenInstanceErrorr   PartialStatePathPreTrainedModelPreTrainedTokenizerBaseProcessorMixinRewardConfigRewardDataCollatorWithPaddingRewardTrainerTrainerTrainerCallbackr	   	_tokenizecompute_accuracydecode_and_strip_paddingdefaultdictdisable_dropout_in_modelgather_objectgenerate_model_cardget_comet_experiment_urlis_rich_availableis_wandb_availablelog_table_to_comet_experimentloggerloggingmaybe_apply_chat_templatenested_detachnnospdprepare_peft_modelprint_rich_tablereplacetorchr   r   r   r(   r-   r2   )*)	dataclassfield)Version)nullcontext)DataCollatorForSeq2SeqDataCollatorForLanguageModeling)ParallelMode)
MethodTypec                 F   ^  [         R                  " T 5      U 4S j5       nU$ )Nc                 8  > [        U S5      (       a5  [        U R                  S5      (       a  U R                  R                  5         T" U /UQ70 UD6n[        U S5      (       a5  [        U R                  S5      (       a  U R                  R                  5         U$ )Nmodelfor_trainingfor_inference)hasattrr>   r?   r@   )selfargskwargsoutputfs       K/home/james-whalen/llama.cpp/unsloth_compiled_cache/UnslothRewardTrainer.pywrapper*prepare_for_training_mode.<locals>.wrapper0   sx     4!!gdjj.&I&IJJ##%4)$)&)4!!gdjj/&J&JJJ$$&    )	functoolswraps)rF   rH   s   ` rG   prepare_for_training_moderM   /   s%    __Q  NrJ   TF)epilogue_fusionmax_autotuneshape_paddingztrace.enabledztriton.cudagraphs)dynamic	fullgraphoptionsc                 d   [         R                  " U R                  SU R                  S   5      SSS9n[         R                  " UR                  S5      SSS9n/ n[	        X#5       H  u  pVUR                  [         R                  5      n[         R                  " USUR                  S5      S9R                  S5      n[         R                  " USS9nXx-
  n	UR                  U	5        M      [         R                  " U5      nUR                  U R                  S   U R                  S   45      nU$ )N   r   )chunksdim)rX   indexrX      )r2   chunkreshapeshapeziptofloat32gather	unsqueezesqueeze	logsumexpappendconcat)
logitsrY   chunked_logitschunked_indexall_per_token_logpschunk_logitschunk_indexselected_logitslogsumexp_valuesper_token_logpss
             rG   chunked_selective_log_softmaxrq   E   s    [[FLL4D!EPQYZ[N[[r!2QaHM%(%G!#u}}5,,|2{G\G\]_G`aiijlm ??<rB)<""?3 &H 	,,':;-55v||AUV6XYrJ   	input_idslogits_to_keeppad_token_idreturnc                 ~    XR                   S   :  a  [        S5      eU SS2SU* 24   nX2:H  nUR                  SS9nU$ )zr
Given prompt tensor, it returns all the left padded tokens in that sequence. so [pad, pad, pad, cat] = 3 tokens 
r[   z8logits_to_keep must be smaller than the sequence length.NrZ   )r^   
ValueErrorsum)rr   rs   rt   prompt_sectionpadding_maskpad_token_countss         rG   calculate_pad_tokens_in_promptr|   W   sX     ++STTq"2N?"223N"2L#''A'.rJ   completion_input_idsleft_pad_tokens_per_promptmax_left_padc                     U R                   u  pEU R                  nX!-
  n[        R                  " XVS9R	                  S5      nXR	                  S5      :  n	X:g  n
X-  nU$ )a)  
Given that we have a sequence, [p,p,p,c,c,c,pad,pad,pad]

Where p are extra prompt tokens we got from slicing the torch tensor, c is completion tokens
and pad are pad tokens, this function would make a completion mask that would 0 out the pad
and p tokens. so in this example [0,0,0,1,1,1,0,0,0]
)devicer   r[   )r^   r   r2   arangerc   )r}   r~   r   rt   
batch_sizecompletion_lenr   num_tokens_to_maskindices
shift_masknon_padding_mask
final_masks               rG    create_completion_attention_maskr   j   si     "6!;!;J!((F%Bll>9CCAFG88;;J,<.JrJ   tensorpad_idc                 l    X:g  n[         R                  " USSSS9n[         R                  " U SU5      nU$ )zD
Moves all padding tokens in each sequence of a batch to the right.
r[   T)rX   
descendingstable)r2   argsortrb   )r   r   masksorted_indicespacked_tensors        rG   left_pack_paddingr      s8     D]]4Q4MNLLN;MrJ   c                     ^  \ rS rSr% Sr\" SSS0S9r\\   \	S'   \" SSS	0S9r
\\   \	S
'   \" SSS0S9r\\   \	S'                                                                                                                                           SU 4S jjrSrU =r$ )UnslothRewardConfig   a  
    
Configuration class for the [`RewardTrainer`].

This class includes only the parameters that are specific to Reward training. For a full list of training
arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this
class may differ from those in [`~transformers.TrainingArguments`].

Using [`~transformers.HfArgumentParser`] we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.

Parameters:
    max_length (`int` or `None`, *optional*, defaults to `1024`):
        Maximum length of the sequences (prompt + completion) in the batch, filters out entries that exceed the
        limit. This argument is required if you want to use the default data collator.
    disable_dropout (`bool`, *optional*, defaults to `True`):
        Whether to disable dropout in the model.
    dataset_num_proc (`int`, *optional*, defaults to `None`):
        Number of processes to use for processing the dataset.
    center_rewards_coefficient (`float`, *optional*, defaults to `None`):
        Coefficient to incentivize the reward model to output mean-zero rewards (proposed by
        https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`.
    remove_unused_columns (`bool`, *optional*, defaults to `False`):
        Whether to remove the columns that are not used by the model's forward pass. Can be `True` only if the
        dataset is pretokenized.

    NhelpzvLLM SamplingParams)defaultmetadatavllm_sampling_paramsrU   z8Chunk size to reduce memory usage. -1 is most efficient.unsloth_num_chunksz'Maximum sequence length to truncate to.max_seq_lengthc                 6  > US:  a  [        SU S35        US:  a  [        SU S35        Uc  U#S:X  a
  U$S:X  a  SnS	n#Wc$  S
SKJn  [        [	        U" 5       S-   S5      S5      n[
        TU ]  " S0 SU_SU_SU_SU_SU_SU_SU_SU_SU	_SU
_SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_S#U_S$U_S%U_S&U_S'U_S(U_S)U_S*U_S+U_S,U_S-U_S.U _S/U!_S0U"_S1U#_S2U$_S3U%_S4U&_S5U'_S6U(_S7U)_S8U*_S9U+_S:U,_S;U-_S<U._S=U/_S>U0_S?U1_S@U2_SAU3_SBU4_SCU5_SDU6_SEU7_SFU8_SGU9_SHU:_SIU;_SJU<_SKU=_SLU>_SMU?_SNW@_SOWA_SPWB_SQWC_SRWD_SSWE_STWF_SUWG_SVWH_SWWI_SXWJ_SYWK_SZWL_S[WM_S\WN_S]WO_S^WP_S_WQ_S`WR_SaWS_SbWT_ScWU_SdWV_SeWW_SfWX_SgWY_ShWZ_SiW[_SjW\_SkW]_SlW^_SmW__SnW`_SoWa_SpWb_SqWc_SrWd_SsWe_StWf_SuWg_SvWh_SwWi_SxWj_SyWk_SzWl_S{Wm_S|Wn_S}Wo_S~Wp_SWq_SWr_SWs_SWt_SWu_SWv_SWw_SWx_SWy_SWz_SW{_SW|_SW}_SW~_SW_SW_SW_SW_SW_SW_SW_WD6  WU l        WU l        WU l	        g )NgHz>z Unsloth: Your learning rate of `zi` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!r[   za` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!steps  unsloth_training_checkpointsnor   )	cpu_countrV      @   
output_diroverwrite_output_dirdo_traindo_eval
do_predicteval_strategyprediction_loss_onlyper_device_train_batch_sizeper_device_eval_batch_sizeper_gpu_train_batch_sizeper_gpu_eval_batch_sizegradient_accumulation_stepseval_accumulation_steps
eval_delaytorch_empty_cache_stepslearning_rateweight_decay
adam_beta1
adam_beta2adam_epsilonmax_grad_normnum_train_epochs	max_stepslr_scheduler_typewarmup_ratiowarmup_steps	log_levellog_level_replicalog_on_each_nodelogging_dirlogging_strategylogging_first_steplogging_stepslogging_nan_inf_filtersave_strategy
save_stepssave_total_limitsave_safetensorssave_on_each_nodesave_only_model'restore_callback_states_from_checkpointno_cudause_cpuuse_mps_deviceseed	data_seedjit_mode_evaluse_ipexbf16fp16fp16_opt_levelhalf_precision_backendbf16_full_evalfp16_full_evaltf32
local_rankddp_backendtpu_num_corestpu_metrics_debugdebugdataloader_drop_last
eval_stepsdataloader_num_workersdataloader_prefetch_factor
past_indexrun_namedisable_tqdmremove_unused_columnslabel_namesload_best_model_at_endmetric_for_best_modelgreater_is_betterignore_data_skipfsdpfsdp_min_num_paramsfsdp_config"fsdp_transformer_layer_cls_to_wrapaccelerator_configparallelism_config	deepspeedlabel_smoothing_factoroptim
optim_args	adafactorgroup_by_lengthlength_column_name	report_toddp_find_unused_parametersddp_bucket_cap_mbddp_broadcast_buffersdataloader_pin_memorydataloader_persistent_workersskip_memory_metricsuse_legacy_prediction_looppush_to_hubresume_from_checkpointhub_model_idhub_strategy	hub_tokenhub_private_repohub_always_pushhub_revisiongradient_checkpointinggradient_checkpointing_kwargsinclude_inputs_for_metricseval_do_concat_batchesfp16_backendpush_to_hub_model_idpush_to_hub_organizationpush_to_hub_tokenmp_parametersauto_find_batch_sizefull_determinismtorchdynamo	ray_scopeddp_timeouttorch_compiletorch_compile_backendtorch_compile_modeinclude_tokens_per_secondinclude_num_input_tokens_seenneftune_noise_alphaoptim_target_modulesbatch_eval_metricseval_on_startuse_liger_kernelliger_kernel_configeval_use_gather_objectaverage_tokens_across_devices
max_lengthdisable_dropoutdataset_num_proccenter_rewards_coefficient )
printmultiprocessingr   minmaxsuper__init__r   r   r   )rB   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r!  r"  r#  r$  r%  r&  r'  r(  r)  r*  r   r   r   rD   r   	__class__s                                                                                                                                              rG   r1  UnslothRewardConfig.__init__   s   X 4)I-  YB  (C  "D1e&F}o  Vw  %x  y-7":zS?P7J M#1"3y{1}a#8"= E	N#E	N#7E	N  E	N 	E	N
 $E	N *E	N $8E	N +FE	N *DE	N (@E	N '>E	N +FE	N '>E	N $E	N '>E	N  *!E	N" (#E	N$ $%E	N& $'E	N( ()E	N* *+E	N,  0-E	N. "/E	N0 !21E	N2 (3E	N4 (5E	N6 "7E	N8 !29E	N:  0;E	N< &=E	N>  0?E	N@ "4AE	NB *CE	ND &<EE	NF *GE	NH $IE	NJ  0KE	NL  0ME	NN !2OE	NP .QE	NR 7^SE	NT UE	NV WE	NX ,YE	NZ [E	N\ "]E	N^ *_E	N`  aE	Nb cE	Nd eE	Nf ,gE	Nh &<iE	Nj ,kE	Nl ,mE	Nn oE	Np $qE	Nr &sE	Nt *uE	Nv !2wE	Nx yE	Nz $8{E	N| $}E	N~ &<E	N@ *DAE	NB $CE	ND  EE	NF (GE	NH %:IE	NJ &KE	NL &<ME	NN %:OE	NP !2QE	NR  0SE	NT UE	NV #6WE	NX &YE	NZ 2T[E	N\ "4]E	N^ "4_E	N` "aE	Nb &<cE	Nd eE	Nf $gE	Nh "iE	Nj .kE	Nl "4mE	Nn "oE	Np *DqE	Nr !2sE	Nt %:uE	Nv %:wE	Nx -JyE	Nz #6{E	N| *D}E	N~ &E	N@ &<AE	NB (CE	ND (EE	NF "GE	NH  0IE	NJ .KE	NL (ME	NN &<OE	NP -JQE	NR *DSE	NT &<UE	NV (WE	NX $8YE	NZ (@[E	N\ !2]E	N^ *_E	N` $8aE	Nb  0cE	Nd &eE	Nf "gE	Nh &iE	Nj *kE	Nl %:mE	Nn "4oE	Np )BqE	Nr -JsE	Nt #6uE	Nv $8wE	Nx "4yE	Nz *{E	N|  0}E	N~ #6E	N@ &<AE	NB -JCE	ND $EE	NF .GE	NH  0IE	NJ *DfKE	NL %9!"4,rJ   )r   r   r   )NNFFFr   FrV   rV   NNr   r   r      g-C6
?g{Gz?g?g+?g:0yE>g      ?g      @rU   linear皙?r   passivewarningTNr   Fr[   Fr   r   NTFFFFFFO  r9  FFFFO1autoFFNrU   NNF FNr   NrU   NNFNFNNFr<  r   NNNNN        
adamw_8bitNFFlengthNNNNTFTFFNN
every_saveNNFNTNFTr;  NNNr<  FFNlasti  FNNFFNNFFFNFTi   TNNNrU   N)__name__
__module____qualname____firstlineno____doc__r5   r   r   r   __annotations__r   intr   r1  __static_attributes____classcell__r2  s   @rG   r   r      s   8 +012+(3-  */VW*#  &+EF&NXc]  #$&'%&#'"&&'"#"%$%""!&!27!'!$!"%) %!& $  -1!!!$%%)  $ $(-"%*!%#!%(,%*!%##' $  $!$)(-"#" "!&(,%)#S]- ]-rJ   r   c                     ^  \ rS rSrSrSS/r            S"S\\\\	R                  4      S\\   S\\   S	\\   S
\\\\\\4   4      S\\\\\\4      S\\/ \4      S\\\/\4      S\\\      S\\R4                  R6                  \R4                  R8                  R:                  4   S\\\R<                  \R<                  /\R<                  4      S\\   4U 4S jjjr  S#S\\\	R                  4   S\\\\R<                  \ 4   4   S\\R<                  \\R<                  \\\R<                  4   4   4   4S jjr! S$S\\\	R                  4   S\\\\R<                  \ 4   4   S\"S\\\      S\\\R<                     \\R<                     \\R<                     4   4
S jjr#U 4S jr$S\%4S jr&U 4S jr'   S%S\\   S\\   S\\\\   S4   4S  jjr(S!r)U =r*$ )&_UnslothRewardTraineri  a
  
Trainer for custom reward.

Args:
    model ([`~transformers.PreTrainedModel`] or `torch.nn.Module`, *optional*):
        Model to be trained, preferably an [`~transformers.AutoModelForSequenceClassification`].
    args ([`RewardConfig`], *optional*):
        Training arguments.
    data_collator ([`~transformers.DataCollator`], *optional*):
        The data collator to use for training. If None is specified, the default data collator
        [`~trainer.utils.RewardDataCollatorWithPadding`] will be used which will pad the sequences to the maximum
        length of the sequences in the batch, given a dataset of paired sequences.
    train_dataset ([`~datasets.Dataset`], *optional*):
        The dataset to use for training.
    eval_dataset ([`~datasets.Dataset`], *optional*):
        The dataset to use for evaluation.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
        Processing class used to process the data. If provided, will be used to automatically process the inputs
        for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
        reuse the fine-tuned model.
    model_init (`Callable[[], transformers.PreTrainedModel]`, *optional*):
        The model initializer to use for training. If None is specified, the default model initializer will be
        used.
    compute_metrics (`Callable[[transformers.EvalPrediction], dict]`, *optional*, defaults to [`~trainer.utils.compute_accuracy`]):
        Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a
        dictionary string to float.
    callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
        Callbacks to use during training.
    optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
        Tuple containing the optimizer and the learning rate scheduler to use for training.
    preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
        Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and
        return the logits to be used for metrics computation.
    peft_config (`dict`, *optional*):
        PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be
        wrapped with the specified PEFT adapter.
trlzreward-trainerNr>   rC   data_collatortrain_dataseteval_datasetprocessing_class
model_initcompute_metrics	callbacks
optimizerspreprocess_logits_for_metricspeft_configc                   >^  UR                  (       a  [        U5        Uc  [        nUc\  Uc  [	        S5      eUR
                  m[        U5      nUR                  (       a   SUl        [        R                  " S5        SU l        OSU l        SUR                  S'   SUR                  ;  a  [        5       R!                  5          SU0nUR#                  [$        SU0S	9nUR#                  [&        SUUR(                  S
9nUR+                  U4S jUR(                  S9nUbT  UR#                  [$        SU0S	9nUR#                  [&        USUR(                  S9nUR+                  U4S jUR(                  S9nS S S 5        [,        TU ]]  UUUUUUUUU	U
US9  [1        U R2                  S5      (       a&  U R2                  R5                  U R6                  5        g g ! [         a    [        USS9n GNf = f! , (       d  f       N= f)NFzYA processing_class must be specified when using the default RewardDataCollatorWithPadding)r   zWhen using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig we have set it for you, but you should do it yourself in the future.Testimate_tokensinput_ids_chosen	tokenizer)	fn_kwargs)batchedr]  num_procc                 V   > [        U S   5      T:*  =(       a    [        U S   5      T:*  $ Nr[  input_ids_rejectedlenxr'  s    rG   <lambda>0_UnslothRewardTrainer.__init__.<locals>.<lambda>O  s.    c!$6"78JFu3qQeOfKgkuKuurJ   )r_  )r]  r^  r_  c                 V   > [        U S   5      T:*  =(       a    [        U S   5      T:*  $ ra  rc  re  s    rG   rg  rh  `  s4    #a(:&;"<
"J #G"6 78JF#GrJ   )r>   rC   rO  rP  rQ  rR  rS  rT  rU  rV  rW  add_model_tags)r/   r(  r!   r   rw   r'  r   r   r   r1   r(   r8  use_reward_data_collatorwarnings_issuedcolumn_namesr   main_process_firstmapr*   r   r)  filterr0  r1  rA   r>   rj  
_tag_names)rB   r>   rC   rO  rP  rQ  rR  rS  rT  rU  rV  rW  rX  r]  r'  r2  s                 @rG   r1  _UnslothRewardTrainer.__init__  s@   (  $U+".O ' o  J9:JKM))F16D. \
 -1D),1D) 48/0]%?%??224(*:;	 - 1 12KXceuWv 1 w - 1 1 '!22	 !2 ! !. 4 4u!22 !5 !  +#/#3#31kK[=\ $4 $L $0#3#3!"+ $!%!6!6	 $4 $L $0#6#6G!%!6!6 $7 $L; 5F 	''%-!+!*G 	 	
 4::/00JJ%%doo6 1Q + F"4uEDF, 54s   #G B0G2G/.G/2
H inputsru   c                    U" US   US   SS9S   nU" US   US   SS9S   nSU;   a7  [         R                  R                  XV-
  US   -
  5      R                  5       * nO0[         R                  R                  XV-
  5      R                  5       * nU R                  R
                  b4  XpR                  R
                  [        R                  " XV-   S	-  5      -  -  nU(       a  UUUS
.4$ U$ )Nr[  attention_mask_chosenT)rr   attention_maskreturn_dictrh   rb  attention_mask_rejectedmarginr   )rewards_chosenrewards_rejected)r,   r   
logsigmoidmeanrC   r*  r2   )rB   r>   rs  return_outputsnum_items_in_batchrz  r{  losss           rG   compute_loss"_UnslothRewardTrainer.compute_lossw  s    /0!"9:
 	
 !12!";<
 	 vMM,,^-NQWX`Qa-abggiiDMM,,^-NOTTVVD99//;II885::~GhmnFn;oooD"0$4   rJ   r   ignore_keysc                   ^ U R                  U5      nTc?  [        U R                  S5      (       a"  [        U R                  R                  S/ 5      mO/ m[
        R                  " 5          U R                  XSS9u  pVS S S 5        U(       a  WS S 4$ WR                  5       n[        U4S jWR                  5        5       5      n[        U5      n[
        R                  " U5      R                  SS9R                  SS9R                  n[
        R                   " UR"                  S   5      nU R                  U5      nXWU4$ ! , (       d  f       N= f)	Nconfigkeys_to_ignore_at_inferenceT)r~  c              3   <   >#    U  H  u  pUT;  d  M  Uv   M     g 7fNr+  ).0kvr  s      rG   	<genexpr>8_UnslothRewardTrainer.prediction_step.<locals>.<genexpr>  s     Q%8TQA[<Pqq%8s   	r   rZ   r   )_prepare_inputsrA   r>   getattrr  r2   no_gradr  detachtupleitemsr+   stackr}  softmaxTzerosr^   )	rB   r>   rs  r   r  r  logits_dictrh   labelss	       `    rG   prediction_step%_UnslothRewardTrainer.prediction_step  s    %%f-tzz8,,%djj&7&79VXZ[ ]]_ $ 1 1%PT 1 UD   $%%{{}Q[%6%6%8QQv& V$))a)088Q8?AAV\\!_-%%f-V##! _s   *E
Ec                 j   > UR                  SS5      nU R                  U5        [        TU ]  " U0 UD6$ )Nnum_print_samplesrV   )popvisualize_samplesr0  evaluate)rB   rC   rD   r  r2  s       rG   r  _UnslothRewardTrainer.evaluate  s9    "JJ':A>01w000rJ   r  c                    U R                  5       n[        [        5      n[        U5       GH  u  pEU R	                  U R
                  USS9u  pFn[        US   U R                  5      n[        US   U R                  5      nUS   R                  [        U5      5        US   R                  [        U5      5        US   R                  [        UR                  5        V	V
s/ s H  o V
s/ s H  n
[        U
S5      PM     sn
PM!     sn
n	5      5        US	:  d  M  [        US   5      U:  d  GM    O   [        R                  " U5      nU R                  R                   S	:X  a  [#        5       (       a  [%        US
U 5        SU R&                  R(                  ;   a1  S	S
KnUR,                  b   UR/                  SUR1                  US905        SU R&                  R(                  ;   a  [3        SUS9  g
g
g
s  sn
f s  sn
n	f )z
Visualize the reward model logits prediction

Args:
    num_print_samples (`int`, defaults to `4`):
        The number of samples to print. Set to `-1` to print all samples.
F)r   r[  rb  chosen_textrejected_textrh   rV   r   Nwandbcompletions)	dataframecomet_mlzcompletions.csv)nametable)get_eval_dataloaderr    list	enumerater  r>   r   rR  extendr"   tolistroundrd  r.   	DataFrameacceleratorprocess_indexr%   r0   rC   r   r  runlogTabler'   )rB   r  eval_dataloaderr  _rs  rh   r  r  item
inner_itemdfr  s                rG   r  '_UnslothRewardTrainer.visualize_samples  s    224D!"?3IA//

FY^/_LAq26:L3MtOdOdeK4V<P5QSWShShiM- ''k(BC/"))-*FG(O""Y_YfYfYhiYhQUtLtj! 4tLYhij !A%#eM.B*CGX*X 4 \\% ))Q. "" $6%6!78$))---99(II}ekkBk.GHITYY000-* 1 /  Mis   !	G8*G3 G83G8c                   > U R                   R                  c*  [        U R                   R                  5      R                  nO(U R                   R                  R                  S5      S   nU R                  US9  [        TU ]!  X5        g )N/rU   )
model_name)	rC   r  r   r   r  splitcreate_model_cardr0  _save_checkpoint)rB   r>   trialr  r2  s       rG   r  &_UnslothRewardTrainer._save_checkpoint  sj    99!!)dii22388J//55c:2>J*5 .rJ   r  dataset_nametagsc                    U R                  5       (       d  g[        U R                  R                  S5      (       ac  [        R
                  R                  U R                  R                  R                  5      (       d!  U R                  R                  R                  nOSnUc  [        5       nO$[        U[        5      (       a  U1nO[        U5      n[        U R                  R                  S5      (       a  UR                  S5        S[        R                  ;   a  UR                  S5        UR                  U R                  5        [        UUU R                   UU[#        5       (       a+  [$        R&                  b  [$        R&                  R(                  OS[+        5       SS9nUR-                  [        R
                  R/                  U R0                  R2                  S	5      5        g)
a  
Creates a draft of a model card using the information available to the `Trainer`.

Args:
    model_name (`str` or `None`, *optional*, defaults to `None`):
        Name of the model.
    dataset_name (`str` or `None`, *optional*, defaults to `None`):
        Name of the dataset used for training.
    tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`):
        Tags to be associated with the model card.
N_name_or_pathunsloth_versionunslothJOB_IDhf_jobsReward)
base_modelr  r  r  r  	wandb_url	comet_urltrainer_namez	README.md)is_world_process_zerorA   r>   r  r-   pathisdirr  set
isinstancestraddenvironupdaterq  r#   r  r&   r  r  urlr$   savejoinrC   r   )rB   r  r  r  r  
model_cards         rG   r  '_UnslothRewardTrainer.create_model_card  sN   " ))++4::$$o66rww}}TZZM^M^MlMl?m?m**88JJ <5Dc""6Dt9D4::$$&788HHYrzz!HHYDOO$(!!**%'9';';		@Ueiimm[_.0!	

 	TYY%9%9;GHrJ   )rk  )NNNNNNNNN)NNNN)FNr  )NNN)+rB  rC  rD  rE  rF  rq  r   r	   r   r,   Moduler   r   r   dictr  r   r   r   r   r   r   r  r   r  r2   r   	Optimizerlr_schedulerLambdaLRr   r1  r   r  boolr  r  rH  r  r  r  rI  rJ  rK  s   @rG   rM  rM    s   $L )*J >B'+04+/EI >BFJ59W
 im&*%t7oryy89:t7 |$t7  -	t7
  (t7 uWd3<.@%@ABt7 #)+=?UWeef
t7 Xb/&9:;t7 "(N+;T+A"BCt7 D12t7 %++//1I1I1R1RRSt7" (0%,,9UW\WcWc9c0d'e#t7$ d^%t7 t7t _bii/0 S%c 1223 
u||U5<<c5<<6G1H#HII	JL ,0$_bii/0$ S%c 1223$ #	$
 d3i($ 
x%x'=x?UU	V$@1
#3 #L/ %)&*,0	4ISM4I sm4I CcD()	4I 4IrJ   rM  c                   F   ^  \ rS rSrSr           SU 4S jjrSrU =r$ )UnslothRewardTraineri   a)
  
    
Trainer for custom reward.

Args:
    model ([`~transformers.PreTrainedModel`] or `torch.nn.Module`, *optional*):
        Model to be trained, preferably an [`~transformers.AutoModelForSequenceClassification`].
    args ([`RewardConfig`], *optional*):
        Training arguments.
    data_collator ([`~transformers.DataCollator`], *optional*):
        The data collator to use for training. If None is specified, the default data collator
        [`~trainer.utils.RewardDataCollatorWithPadding`] will be used which will pad the sequences to the maximum
        length of the sequences in the batch, given a dataset of paired sequences.
    train_dataset ([`~datasets.Dataset`], *optional*):
        The dataset to use for training.
    eval_dataset ([`~datasets.Dataset`], *optional*):
        The dataset to use for evaluation.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
        Processing class used to process the data. If provided, will be used to automatically process the inputs
        for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
        reuse the fine-tuned model.
    model_init (`Callable[[], transformers.PreTrainedModel]`, *optional*):
        The model initializer to use for training. If None is specified, the default model initializer will be
        used.
    compute_metrics (`Callable[[transformers.EvalPrediction], dict]`, *optional*, defaults to [`~trainer.utils.compute_accuracy`]):
        Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a
        dictionary string to float.
    callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
        Callbacks to use during training.
    optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
        Tuple containing the optimizer and the learning rate scheduler to use for training.
    preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
        Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and
        return the logits to be used for metrics computation.
    peft_config (`dict`, *optional*):
        PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be
        wrapped with the specified PEFT adapter.

    c                 0  > Uc
  [        5       n[        USS5      n[        U5      [        La  Sn[        USS5      n[        U5      [        La  SnSn[        R
                  R                  SS5      S:H  nU(       d1  [        R
                  R                  SS5      S:X  a  [        S5        S	n[        R
                  R                  S
S5      n[        UR                  SS 5      =(       d    [        UR                  SS 5      nUc  UR                  5       R                  nSSKJn  U" U5      nU[        R                  :H  nU(       d  U(       a  U(       a  [        S5      eU(       d  U(       d  U(       a  [        S5      eU(       a"  SUl        SUl        S[        R
                  S'   OCU(       d<  U(       d5  US:X  a/  UUl        U(       + Ul        U(       a  SOS[        R
                  S'   [        USS 5      b-  [        USS5      S:X  a  SUl        [        USS 5      c  SUl        [        USS 5      nUb/  US:  a)  SSKJn  [-        U5      [-        S5      ::  a  [        S5        [        USS5      S:w  aL  [        USS5      nUS:X  a!  UR.                  U:  a  UR.                  Ul        [        US S 5      c
  Ub  UUl        [        US!S5      n[        U5      [        La  Sn[        US"S5      n[        U5      [        La  SnUR                   (       a  U(       a  SUl        S	Ul        UR"                  (       a  U(       a  S	Ul        SUl        U(       a  SUl        SUl        Oc[        R
                  R                  S
S5      S#:X  a  S	Ul        SUl        O0U(       d)  U(       d"  UR"                  Ul        UR                   Ul        Sn[9        5       R                  S$S 5      b  S	n[9        5       R                  S%S 5      b  S	nU(       a  S[        R
                  S&'   S'[9        5       ;  a  [;        US'5      (       d  OD[        US'S 5      n[        US'S 5      nUc'  Ub$  UR<                  n[;        US'5      (       a  UUl        Ub!  [;        US(5      (       a  UR?                  5         S)[9        5       ;   a   [;        [@        S*5      (       a  S+[@        l!        S,[9        5       ;   aU  [;        US*5      (       a  S+Ul!        [;        US)5      (       a,  [;        UR@                  S*5      (       a  S+UR@                  l!        S,[9        5       ;   a  UO[@        nSS-K"J#n  [I        UU5      (       dx  [I        U[J        5      (       a(  S.URL                  ;  a  [O        USS/[        US0S 5      S19nO[I        U[N        5      (       a%  S.URL                  ;   a  [K        U[        US0S 5      S29nOJ[;        US35      (       a  SUl(        [;        US45      (       a  S5Ul)        [;        US65      (       a	  S7S	0Ul*        [I        UU5      (       dx  [;        US85      (       dg  [;        US)5      (       aV  [I        U[J        5      (       a   [K        UR@                  [        US0S 5      S29nO![O        UR@                  SS/[        US0S 5      S19n/ n SS9K+J,n!  U!" S:U 5        [        US;S 5      [Z        R\                  :X  a(  UR^                  S:  a  [        US<S5      S:w  a  SUl0        S=[9        5       ;   a!  [;        US(5      (       a  UR?                  5         [b        T$U ]  " SDUUUUUUUUU	U
US>.UD6  S=[9        5       ;   a!  [;        US?5      (       a  URg                  5         [;        U S@5      (       a-  U Rh                  Rk                  5         [;        U S@5      (       a  U ?4[        USAS 5      b  U Rl                  UR                  5       l6         [;        U SB5      (       aV  U Rn                  Rp                  n"Un#[;        U#S=5      (       a&  U"U#l9        U#Rt                  n#[;        U#S=5      (       a  M&  U"U#l9         [;        U SC5      (       a.  [w        [y        U Rz                  R|                  5      U 5      U l>        g )ENr   Fr   UNSLOTH_ENABLE_FULL_FINETUNING01UNSLOTH_FORCE_FLOAT32zKUnsloth: Switching to float32 training since model cannot work with float16TUNSLOTH_MIXED_PRECISIONra   dtypetorch_dtyper   )
_get_dtypezuUnsloth: Model is in float16 precision but you want to use bfloat16 precision. Set fp16 to `True` and bf16 to `False`zuUnsloth: Model is in bfloat16 precision but you want to use float16 precision. Set fp16 to `False` and bf16 to `True`r   ACCELERATE_MIXED_PRECISIONrQ  r   r   r   r6  r   r[   )__version__z4.45.2z**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!
`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`r      r   r   r   bfloat16rT  rW  UNSLOTH_RETURN_LOGITSr   r?   r\  padding_siderightrR  )UnslothVisionDataCollatorr  r=  pad_to_multiple_of)mlmmlm_probabilityr  )r  r   dataset_text_fieldr<  dataset_kwargsskip_prepare_datasetpad)PatchRLStatisticsreward_trainerparallel_mode_n_gpur>   )r>   rC   rO  rP  rQ  rR  rS  rT  rU  rW  rX  r@   neftune_hook_handler  r  trainr+  )?r   r  typer  r-   r  getr,  r  get_input_embeddingsr  unsloth_zoo.utilsr  r2   float16	TypeErrorr   r   r   r   transformersr  r6   r   r   r   r   r   localsrA   r   r?   r\  r  unsloth_zoo.vision_utilsr  r  r8   rm  +TransformersDataCollatorForLanguageModelingr   r  r  unsloth_zoo.logging_utilsr   r:   NOT_DISTRIBUTEDn_gpur  r0  r1  r@   r  remover  r  scaleraccelerator_scalerr>   r;   rM   r2  r  )%rB   r>   rC   rO  rP  rQ  rR  rS  rT  rU  rW  rX  rD   use_bf16use_fp16force_float32full_finetuningmixed_precision_dtyper  r  r
  ga_stepstransformers_versioneval_bszr   r   _output_logitsmodel_max_seq_lengthargs_max_seq_lengthr    _UnslothRewardTrainer__tokenizerr  other_metricsr   r  current_modelr2  s%                                       rG   r1  UnslothRewardTrainer.__init__H  s    < 3 54/>%%x4/>%%x**..)I3OSVVBJJNN3JC$PTW$W_` M "

/H) Tgt4bm]a8b=%"<"<">"D"D%05!5==('hy  JA  @B  :Bg(9  NE  DF  >FDIDI7;BJJ3481F)1SDI#DIAHvfBJJ344.:wt_^b?cgk?k!(Dt\408C$/4!>EHqLH+,0AA @ A4$/47t%A1EH1}!A!AH!Lpt  qQ  qQdNmt6=E(J^  @H`d`| '7?t+e^ '7?t+e^99u)<\`dFY99t)<[`TEX"'D"'DZZ^^5yAZO"&D"'D"&))D"&))D8<<)40<tn8<<7>J]aN25BJJ./68+GDBR4S4S#*52BD#I #*42BD#I"*/C/O!&!5!54!122.D4G!?!? &("wy.'I'Idk9Ka)'88Za:J:W'55'BRB\B\^l:m:m  Zao  pJ  pJ  pW*<*H&iF-)BCC-)?@@XUbUoUoEo K&))07KT)R	! M+VWW\dhu  iC  iC  ]C 6)07KT)R!
 t455TYt7Qt122bD4Kt-..G]_cFd0C-)BCC;..7;3T3Tm-CDD$:#---4T;OQU-V%M
 %P#--#*--4T;OQU-V	%M ?*M: 4$/<3O3OOTXT^T^abTbtXq)Q.fh75.#A#A  	0))'/#-!,I%	0 )/	0 fh75/#B#B!4.//$$++-t2339Q4.5A?C?W?WE&&(<4''%%,,F!M-11390 - 3 3 -11 06M,4!!#$=dnn>R>R$SUYZDJrJ   )r  )NNNNNNNNNNN)rB  rC  rD  rE  rF  r1  rI  rJ  rK  s   @rG   r  r     s8    &R (,e erJ   r  	addFilterc                        \ rS rSrS rS rSrg)HideLoggingMessagei  c                     Xl         g r  text)rB   r*  s     rG   r1  HideLoggingMessage.__init__  s    d)rJ   c                 <    U R                   UR                  5       ;  $ r  )r*  
getMessage)rB   rf  s     rG   rp  HideLoggingMessage.filter  s    alln)DErJ   r)  N)rB  rC  rD  rE  r1  rp  rI  r+  rJ   rG   r'  r'    s    2ErJ   r'  z`use_cache=True`)VrF  r2   r   torch.nnr,   r   Ftypingr   r   r   r   r	   r
   r   r   trl.trainer.reward_trainerr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r-   r.   r/   r0   r1   dataclassesr4   r5   packaging.versionr6   numpynp
contextlibr7   r  r8   r9   r  transformers.training_argsr:   rK   typesr;   rM   torch_compile_optionscompilerq   rH  r|   r   r   r   rM  r  rA   Filterr'  r%  r+  rJ   rG   <module>r=     s  0    $ I I I j  j  j  j  j  j  j  j  j  j  j  j  j 
  ( %   " $  3      4;PR S"||  \\	&,, %  	
 \\6ell C ELL  F-, F- F-N
 GIG GIP
M0 M^  6;FW^^ F 	
'(:;<  rJ   