
    f:i=|             
          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/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>J?r?J@r@JArAJrJBrBJCrCJDrDJErEJFrFJGrGJHrHJIrIJJrJJKrKJLrLJrJMrMJrJ
r
J r J!r!J'r'J7r7J=r=JDrDJr  SSKDrDSSK7  SSKNJOrOJPrP  SS	KQJRrR  SSKrSSKSrBSS
KTJCrC  SSKJr  SSKUJVrVJWrX  SSKYJZrZ  SSK[r[SSK\J]r]  S r^ SSSSSS.r_\R                  " SS\_S9S 5       raS\R                  S\bS\bS\R                  4S jrcS\R                  S\R                  S\bS\bS\R                  4
S jrdS\R                  S\bS\R                  4S jre\O " S  S!\5      5       rf  " S" S#\'5      rg " S$ S%\g5      rh \i" \=S&5      (       a3  SSK>r> " S' S(\>R                  5      rk \=R                  " \k" 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)Mr   AutoModelForCausalLM	BCOConfig
BCOTrainerBaseImageProcessorCLF_NAMEr   DPODataCollatorWithPaddingDataCollator
DataLoaderDatasetEvalLoopOutputFFeatureExtractionMixinLiteralLogisticRegressionr   PartialStatePath	PeftModelPreTrainedModelPreTrainedTokenizerBaseProcessorMixinRUNNING_NAMERunningMomentsSequentialSamplerTrainerTrainerCallbackTrainingArgumentsr	   _process_tokens	_tokenizeautocastcontextmanagercreate_reference_modeldefaultdictdisable_dropout_in_modelgenerate_model_cardget_comet_experiment_url
has_lengthinspectis_comet_availableis_joblib_availableis_peft_availableis_sklearn_availableis_wandb_available
itemgetterjobliblog_table_to_comet_experimentloggerloggingmaybe_apply_chat_templatemaybe_extract_promptmaybe_unpair_preference_datasetnnnpnullcontextospad_to_lengthpdpeft_module_casting_to_bf16prepare_deepspeedprepare_model_for_kbit_trainingrandomselective_log_softmaxtextwraptorchtqdmr   r   r   r   r$   r4   r:   rB   rK   )*)	dataclassfield)Version)rA   )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)hasattrrW   rX   rY   )selfargskwargsoutputfs       >/home/james-whalen/unsloth_compiled_cache/UnslothBCOTrainer.pywrapper*prepare_for_training_mode.<locals>.wrapper0   sx     4!!gdjj.&I&IJJ##%4)$)&)4!!gdjj/&J&JJJ$$&    )	functoolswraps)r_   ra   s   ` r`   prepare_for_training_moderf   /   s%    __Q  Nrc   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)rq   indexrq      )rK   chunkreshapeshapeziptofloat32gather	unsqueezesqueeze	logsumexpappendconcat)
logitsrr   chunked_logitschunked_indexall_per_token_logpschunk_logitschunk_indexselected_logitslogsumexp_valuesper_token_logpss
             r`   chunked_selective_log_softmaxr   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rc   	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 
rt   z8logits_to_keep must be smaller than the sequence length.Nrs   )rw   
ValueErrorsum)r   r   r   prompt_sectionpadding_maskpad_token_countss         r`   calculate_pad_tokens_in_promptr   W   sX     ++STTq"2N?"223N"2L#''A'.rc   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   rt   )rw   r   rK   aranger|   )r   r   r   r   
batch_sizecompletion_lenr   num_tokens_to_maskindices
shift_masknon_padding_mask
final_masks               r`    create_completion_attention_maskr   j   si     "6!;!;J!((F%Bll>9CCAFG88;;J,<.Jrc   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.
rt   T)rq   
descendingstable)rK   argsortr{   )r   r   masksorted_indicespacked_tensors        r`   left_pack_paddingr      s8     D]]4Q4MNLLN;Mrc   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$ )UnslothBCOConfig   u)  
    
Configuration class for the [`BCOTrainer`].

This class includes only the parameters that are specific to BCO 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. This argument is required if you want
        to use the default data collator.
    max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
        Maximum length of the prompt. This argument is required if you want to use the default data collator.
    max_completion_length (`int` or `None`, *optional*, defaults to `None`):
        Maximum length of the completion. This argument is required if you want to use the default data collator
        and your model is an encoder-decoder.
    beta (`float`, *optional*, defaults to `0.1`):
        Parameter controlling the deviation from the reference model. Higher β means less deviation from the
        reference model.
    label_pad_token_id (`int`,  *optional*, defaults to `-100`):
        Label pad token id. This argument is required if you want to use the default data collator.
    padding_value (`int` or `None`, *optional*, defaults to `None`):
        Padding value to use. If `None`, the padding value of the tokenizer is used.
    truncation_mode (`str`, *optional*, defaults to `"keep_end"`):
        Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`.
        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 and reference model.
    generate_during_eval (`bool`, *optional*, defaults to `False`):
        If `True`, generates and logs completions from both the model and the reference model to W&B or Comet
        during evaluation.
    is_encoder_decoder (`bool` or `None`, *optional*, defaults to `None`):
        When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument,
        you need to specify if the model returned by the callable is an encoder-decoder model.
    precompute_ref_log_probs (`bool`, *optional*, defaults to `False`):
        Whether to precompute reference model log probabilities for training and evaluation datasets. This is
        useful when training without the reference model to reduce the total GPU memory needed.
    model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
        Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
        string.
    ref_model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
        Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the reference model
        from a string.
    dataset_num_proc (`int` or `None`, *optional*, defaults to `None`):
        Number of processes to use for processing the dataset.
    prompt_sample_size (`int`, *optional*, defaults to `1024`):
        Number of prompts that are fed to density ratio classifier.
    min_density_ratio (`float`, *optional*, defaults to `0.5`):
        Minimum value of the density ratio. The estimated density ratio is clamped to this value.
    max_density_ratio (`float`, *optional*, defaults to `10.0`):
        Maximum value of the density ratio. The estimated density ratio is clamped to this value.

    NhelpzvLLM SamplingParams)defaultmetadatavllm_sampling_paramsrn   z8Chunk size to reduce memory usage. -1 is most efficient.unsloth_num_chunksz'Maximum sequence length to truncate to.max_seq_lengthc                   > 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_SW_SW_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!rt   za` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!steps  unsloth_training_checkpointsnor   )	cpu_countro      @   
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max_prompt_lengthmax_completion_lengthbetalabel_pad_token_idpadding_valuetruncation_modedisable_dropoutgenerate_during_evalis_encoder_decoderprecompute_ref_log_probsmodel_init_kwargsref_model_init_kwargsdataset_num_procprompt_sample_sizemin_density_ratiomax_density_ratio )
printmultiprocessingr   minmaxsuper__init__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/  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  rA  rB  rC  rD  rE  rF  rG  rH  rI  rJ  rK  rL  rM  rN  rO  rP  rQ  r   r   r   r]   r   	__class__s                                                                                                                                                           r`   rX  UnslothBCOConfig.__init__   s   r 4)I-  YB  (C  "D1e&F}o  Vw  %x  y-7":zS?P7J M#1"3y{1}a#8"= R	<#R	<#7R	<  R	< 	R	<
 $R	< *R	< $8R	< +FR	< *DR	< (@R	< '>R	< +FR	< '>R	< $R	< '>R	<  *!R	<" (#R	<$ $%R	<& $'R	<( ()R	<* *+R	<,  0-R	<. "/R	<0 !21R	<2 (3R	<4 (5R	<6 "7R	<8 !29R	<:  0;R	<< &=R	<>  0?R	<@ "4AR	<B *CR	<D &<ER	<F *GR	<H $IR	<J  0KR	<L  0MR	<N !2OR	<P .QR	<R 7^SR	<T UR	<V WR	<X ,YR	<Z [R	<\ "]R	<^ *_R	<`  aR	<b cR	<d eR	<f ,gR	<h &<iR	<j ,kR	<l ,mR	<n oR	<p $qR	<r &sR	<t *uR	<v !2wR	<x yR	<z $8{R	<| $}R	<~ &<R	<@ *DAR	<B $CR	<D  ER	<F (GR	<H %:IR	<J &KR	<L &<MR	<N %:OR	<P !2QR	<R  0SR	<T UR	<V #6WR	<X &YR	<Z 2T[R	<\ "4]R	<^ "4_R	<` "aR	<b &<cR	<d eR	<f $gR	<h "iR	<j .kR	<l "4mR	<n "oR	<p *DqR	<r !2sR	<t %:uR	<v %:wR	<x -JyR	<z #6{R	<| *D}R	<~ &R	<@ &<AR	<B (CR	<D (ER	<F "GR	<H  0IR	<J .KR	<L (MR	<N &<OR	<P -JQR	<R *DSR	<T &<UR	<V (WR	<X $8YR	<Z (@[R	<\ !2]R	<^ *_R	<` $8aR	<b  0cR	<d &eR	<f "gR	<h &iR	<j *kR	<l %:mR	<n "4oR	<p )BqR	<r -JsR	<t #6uR	<v $8wR	<x "4yR	<z *{R	<|  0}R	<~ #6R	<@ &<AR	<B -JCR	<D $ER	<F !2GR	<H %:IR	<J KR	<L "4MR	<N *OR	<P .QR	<R .SR	<T $8UR	<V "4WR	<X (@YR	<Z !2[R	<\ %:]R	<^  0_R	<` "4aR	<b !2cR	<d !2FeR	<f %9!"4,rc   )r   r   r   )NNFFFr   Fro   ro   NNr   r   r      g-C6
?g{Gz?g?g+?:0yE>g      ?g      @rn   linear皙?r   passivewarningTNr   Frt   Fr   r   NTFFFFFFO  ra  FFFFO1autoFFNrn   NNF FNr   Nrn   NNTNFNNFrd  r   NNNNN        
adamw_8bitNFFlengthNNNNTFTFFNN
every_saveNNFNTNFTrc  NNNrd  FFNlasti  FNNFFNNFFFNFT      Nr^  Nkeep_endTFNFNNNrj  g      ?g      $@Nrn   N)__name__
__module____qualname____firstlineno____doc__rO   r   r   r   __annotations__r   intr   rX  __static_attributes____classcell__rY  s   @r`   r   r      sB   9t +012+(3-  */VW*#  &+EF&NXc]  #$&'%&#'"&&'"#"%$%""!&!27!'!$!"%) $!& $  -1!!!$%%)  $ $(-"%*!%#!%(,%*!%##' $  $!$)(-"#" "!&(, $!$$!#(  $! #mw- w-rc   r   c            $       0	  ^  \ rS rSrSrSS/r                 STS\\\R                  \
4   S\\\\R                  \
4      S\S	\\   S
\\\\\
\4   4      S\\\\\\4      S\\   S\\/ \4      S\\\      S\\R2                  R4                  \R2                  R6                  R8                  4   S\\\R:                  \R:                  /\R:                  4      S\\   S\\\/\4      S\\
   S\\
   S\\   S\\   4"U 4S jjjr\ S 5       r!S\RD                  S\RD                  4S jr#S\RH                  S\RH                  S\RD                  4S jr%S\\
\\\RH                  4   4   S\\RD                  \RD                  4   4S  jr&SUS!\S"\'S\RD                  4S# jjr(U 4S$ jr)U 4S% jr*\+S& 5       r,S\-4U 4S' jjr.SVS
\\   S\-4U 4S( jjjr/S)\S\4S* jr0\1   SWS+\RD                  S,\RH                  S-\2S.\'S/\2S\RD                  4S0 jj5       r3S\R                  S\\
\\\RH                  4   4   S\\RD                  \RD                  \RD                  \RD                  4   4S1 jr4S2\RD                  S\RD                  4S3 jr5 SXS4\RD                  S5\RD                  S6\RD                  S7\RD                  S8\\RD                     S2\\RD                     S9\2S\\RD                  \RD                  \RD                  \RD                  4   4S: jjr6 SXS\\
\\\RH                  4   4   S9\24S; jjr7  SYS\\\R                  4   S<\\
\\R:                  \84   4   S\\R:                  \\R:                  \\
\R:                  4   4   4   4S= jjr9SZS>\\
\:4   S?\;S@   SS4SA jjr<SVS!\\   S\\Rz                  R|                  R~                     4SB jjr@S\\
\RH                  4   S\\
\
4   4SC jrA SVS\\\R                  4   S<\\
\\R:                  \84   4   SD\2SE\\\
      4SF jjrB   S[SG\-SH\
SD\\2   SE\\\
      SI\
S\4U 4SJ jjjrCSVSK\\
\:4   SL\\:   SS4U 4SM jjjrDU 4SN jrE   S\SO\\
   SP\\
   SQ\\
\\
   S4   4SR jjrFSSrGU =rH$ )]_UnslothBCOTraineri  a*  
Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper.

Args:
    model (`transformers.PreTrainedModel`):
        The model to train, preferably an `AutoModelForSequenceClassification`.
    ref_model (`PreTrainedModelWrapper`):
        Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
        and loss. If no reference model is provided, the trainer will create a reference model with the same
        architecture as the model to be optimized.
    args (`BCOConfig`):
        The arguments to use for training.
    train_dataset (`datasets.Dataset`):
        The dataset to use for training.
    eval_dataset (`datasets.Dataset`):
        The dataset to use for evaluation.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*, defaults to `None`):
        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.
    data_collator (`transformers.DataCollator`, *optional*, defaults to `None`):
        The data collator to use for training. If None is specified, the default data collator
        (`DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the
        sequences in the batch, given a dataset of paired sequences.
    model_init (`Callable[[], transformers.PreTrainedModel]`):
        The model initializer to use for training. If None is specified, the default model initializer will be
        used.
    callbacks (`list[transformers.TrainerCallback]`):
        The callbacks to use for training.
    optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
        The optimizer and scheduler to use for training.
    preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
        The function to use to preprocess the logits before computing the metrics.
    peft_config (`dict`, defaults to `None`):
        The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
        a PEFT model.
    compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
        The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
        metric values.
    model_adapter_name (`str`, defaults to `None`):
        Name of the train target PEFT adapter, when using LoRA with multiple adapters.
    ref_adapter_name (`str`, defaults to `None`):
        Name of the reference PEFT adapter, when using LoRA with multiple adapters.
trlbcoNrW   	ref_modelr\   train_dataseteval_datasetprocessing_classdata_collator
model_init	callbacks
optimizerspreprocess_logits_for_metricspeft_configcompute_metricsmodel_adapter_nameref_adapter_nameembedding_funcembedding_tokenizerc                   > Ub)  [        5       (       a  [        5       (       d  [        S5      e[        U5      [        L a  [        S5      e[        U[        5      (       d  Ub  X!L a  [        S5      eUR                  c  0 nO[        U[        5      (       d  [        S5      eUR                  nUR                  S5      nUbd  [        U[        5      (       a  US:w  a  [        [        U5      nUS:w  a.  [        U[        R                  5      (       d  [        SU S35      eUUS'   UR                  c  0 nO[        U[        5      (       d  [        S	5      eUR                  nUR                  S5      nUbd  [        U[        5      (       a  US:w  a  [        [        U5      nUS:w  a.  [        U[        R                  5      (       d  [        SU S35      eUUS'   [        U[        5      (       a  [        R                  " U40 UD6n[        U[        5      (       a  [        R                  " U40 UD6nS
U l        [#        5       (       d  Ub  [        S5      e[#        5       (       GaN  UGbJ  [        U[$        5      (       a  UR'                  5       n[        USS
5      (       d  [        USS
5      (       at  [)        US5      =(       a0    S[+        [,        R.                  " [0        5      R2                  5      ;   nSUR4                  0nU(       a  UR6                  US'   [1        U40 UD6nOUUR4                  (       aD  [)        US5      (       a  UR9                  5         O"S nUR;                  5       R=                  U5        UnUR>                  (       a$  [        USS
5      (       a  [A        U5        SU l        OUUR4                  (       aD  [)        US5      (       a  UR9                  5         O"S nUR;                  5       R=                  U5        URB                  (       a)  [E        5       (       d  [G        5       (       d  [        S5      eUb  URH                  RJ                  U l%        O)URJ                  c  [        S5      eURJ                  U l%        [#        5       =(       a    [        U[$        5      U l&        Xl'        Xl(        U(       a  X l)        O:U RL                  (       d  URT                  (       a  S U l)        O[W        U5      U l)        Uc  [        S5      eURX                  c  [Z        R\                  " S5        SnURX                  b  URX                  nUR^                  c  [Z        R\                  " S5        SnUR^                  b  UR^                  nS nUR`                  c)  U RJ                  (       a  [Z        R\                  " S5        SnUR`                  b  U RJ                  (       a  UR`                  nUc_  [c        URd                  URf                  U RJ                  S9nURh                  (       a  S
Ul4        [Z        R\                  " S5        SU l5        OS
U l5        URl                  (       a-  [o        U5        U RR                  b  [o        U RR                  5        WU l,        URB                  U l!        URf                  U l3        URp                  b  URp                  OURd                  U l8        WU l/        URr                  U l9        UU l0        URT                  U l*        S
U l:        S
U l;        [y        S 5      U l=        UR|                  U l>        [        URH                  SS
5      U l?        [        URH                  S S!5      U l@        U R~                  (       a&  U R                  S!:X  a  [Z        R\                  " S"5        UU lA        UU lB        SUR                  S#'   [        5       R                  5          UR                  [        UR                  S$S%9n[        XCR                  S&S'9nUR                  [        S(U0UR                  S)9nUbT  UR                  [        UR                  S*S%9n[        XSR                  S+S'9nUR                  [        S(U0UR                  S)9nUR                  [        SX`R                  S,.UR                  S-S.9nS/U RJ                  UU RX                  U Rr                  U Rf                  U R^                  U R`                  S0.nUR                  [        UUR                  S1S29nUb  UR                  [        X`R                  S,.SUR                  S3S49nS/U RJ                  UU RX                  U Rr                  U Rf                  U R^                  U R`                  S0.nUR                  [        UUR                  S5S29nUR                  S6 UR                  S7S%9nUR                  S8 UR                  S9S%9nS S S 5        [        T$U G]=  UUUUUUUUU	U
US:9  S
U lP        [)        U R                  S;5      (       a%  U R                  R                  U R                  5        [)        U S<5      (       d  [        S=5      eU R                  (       aJ  U R                  R                  R                  R                  S>:X  a  U RT                  (       a  [        S?5      eU RR                  c.  U RL                  (       d  U RT                  (       d  [        S@5      eO`U R                  (       a&  [        U RR                  U R                  5      U l)        O)U R                  R                  U RR                  SSA9U l)        [        U R                  SB9U l]        U R                  b  UR                  (       a  g U R                  WU R                  R                  SC9nU R                  WU R                  R                  SC9n[        R                  " UU4SDSE9n [        R                  " [        R                  " US S 2SD4   5      [        R                  " US S 2SD4   5      4SDSE9n![        SFSG9R                  U R                  5       R                  5       R                  5       U!R                  5       R                  5       5      U lj        U R                  R                  UR                  5       R                  5       R                  5       [        R                  " US S 2SD4   5      R                  5       R                  5       5      n"U R                  R                  UR                  5       R                  5       R                  5       [        R                  " US S 2SD4   5      R                  5       R                  5       5      n#[Z        R                  " SHU" SIU# 35        g ! , (       d  f       GN= f)JNz}BCOTrainer with UDM requires the scikit-learn and joblib libraries. Please install it with `pip install scikit-learn joblib`.z3Please use `BCOConfig` instead `TrainingArguments`.z`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the same as `model`, you must mass a copy of it, or `None` if you use peft.zRYou passed model_kwargs to the BCOTrainer. But your model is already instantiated.dtyperc  zhInvalid `dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got .zZYou passed ref_model_kwargs to the BCOTrainer. But your ref_model is already instantiated.FzPEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT modelsis_loaded_in_8bitis_loaded_in_4bitr'  use_gradient_checkpointingenable_input_require_gradsc                 &    UR                  S5        g NTrequires_grad_moduleinputr^   s      r`   make_inputs_require_grad=_UnslothBCOTrainer.__init__.<locals>.make_inputs_require_grad  s    --d3rc   Tc                 &    UR                  S5        g r  r  r  s      r`   r  r    s    ))$/rc   z`generate_during_eval=True` requires Weights and Biases or Comet to be installed. Please install `wandb` or `comet-ml` to resolve.zMWhen no model is provided, you need to pass the parameter is_encoder_decoder.zdmax_length or a processing_class must be specified when using the default DPODataCollatorWithPaddingzWhen using DPODataCollatorWithPadding, you should set `max_length` in the `BCOConfig`. It will be set to `512` by default, but you should do it yourself in the future.rk  zWhen using DPODataCollatorWithPadding, you should set `max_prompt_length` in the `BCOConfig`. It will be set to `128` by default, but you should do it yourself in the future.   zWhen using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the BCOTrainer's init it will be set to `128` by default, but you should do it yourself in the future.)r   rE  rJ  zWhen using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your BCOConfig we have set it for you, but you should do it yourself in the future.c                       [        [        5      $ N)r,   listrR  rc   r`   <lambda>-_UnslothBCOTrainer.__init__.<locals>.<lambda>)  s	    ;t3Drc   output_router_logitsrouter_aux_loss_coefre  a-  You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to `0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary loss.estimate_tokensz$Extracting prompt from train dataset)num_procdesczUnpairing train dataset)r  	tokenizer)	fn_kwargsr  z#Extracting prompt from eval datasetzUnpairing eval dataset)r  r  zTokenizing train dataset)batchedr  r  r  rd  )prefixrJ  r  rA  rG  rE  rB  rC  z"Processing tokenized train dataset)r  r  r  zTokenizing eval dataset)r  r  r  r  z!Processing tokenized eval datasetc                     U S   $ NlabelrR  xs    r`   r  r    s    !G*rc   zFiltering desirable examplesc                     U S   (       + $ r  rR  r  s    r`   r  r    s
    aj.rc   zFiltering undesirable examples)rW   r\   r  r}  r~  r  r  r  r  r  r  add_model_tagsacceleratorzXYour `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`.   zrYou cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`.z]No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`)evaluation_mode)r  )sample_sizer   rs   balanced)class_weightz(UDM classifier training scores: chosen: z, rejected: )mr5   r3   ImportErrortyper&   r   
isinstancestrrL  getgetattrrK   r  rM  r   from_pretrained_peft_has_been_casted_to_bf16r4   r   merge_and_unloadrZ   r  r1   	signaturerG   
parametersr&  r'  r  get_input_embeddingsregister_forward_hookr   rE   rI  r6   r2   configrJ  is_peft_modelr  r  r|  rK  r+   rA  r:   r`  rB  rC  r   r   rE  r  use_dpo_data_collatorrH  r-   rF  rG   _precomputed_train_ref_log_probs_precomputed_eval_ref_log_probsr,   _stored_metricsrD  aux_loss_enabledaux_loss_coefr  r  warnings_issuedr   main_process_firstmapr=   rN  r>   r<   r(   r'   filterrW  rX  model_accepts_loss_kwargsrW   r  
_tag_namesAttributeErroris_deepspeed_enabledr  statedeepspeed_plugin
zero_stagerF   prepare_modelr"   runningr  _get_sample_prompt_embeddingsr\   rO  cat	ones_like
zeros_liker   fitcpufloatnumpyclfscoreinfo)%r[   rW   r|  r\   r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  rL  r  rM  _support_gc_kwargsprepare_model_kwargsr  rA  rB  rC  r  	desirableundesirablechosen_embeddingsrejected_embeddings
embeddingslabelschosen_meanrejected_meanrY  s%                                       r`   rX  _UnslothBCOTrainer.__init__@  s   , %/C/E/EJ]J_J_ P  :**RSS%%%%*;	@RZ 
 !!) "E3''qrr $ 6 6%))'2E eS))evo#E51EF?:eU[[+I+I$ C  DI  CJ  JK  L  .3!'*%%-$&!Is++l  %)$>$>!)--g6E eS))evo#E51EF?:eU[[+I+I$ C  DI  CJ  JK  L  27%g.eS!!(88TBSTEi%%,<<Y`J_`I .3* ""{'> a    [%<%++..0u1599WUL_af=g=g%,9& &5%%&EFQQ:  # )EdFaFa'b$%LPLnLn()HI7VAUV,,5">??4464 ..0FFG_` EyyWU,?GG+E2592
 ((u:;;0020 **,BBC[\$$.@.B.BFXFZFZD 
 &+ll&E&ED#$$,lmm&*&=&=D#.0QZy5Q"4 0&N4#@#@!DN3E:DN#v  ??"NNc J??&J!!)NNc !$!!- $ 6 6 $%%-$2I2INNd %(!%%1d6M6M$($>$>! 6-::#'#:#:#'#:#:M ))-2*\
 *.D&).D& $U+~~)(8$$($=$=!"&"9"9373E3E3QT//WgWtWt!2#33%:"(,(E(E% 16-/4,  ++DE II	 '6Le T$U\\3I3O  T%7%73%>NN -#6  48/0^..0)--$t/D/DKq . M <44;TM *--)kCS5T_c_t_t . M '+//(43H3HOt  0    ? "7"7>V   ,//-*,<=!22  0   *--(8QiQij../ . M &*&=&=-"oo#'#7#7&*&=&=%)%;%;)-)C)C	I *--#..9	 . M '+//,<UmUmn !222  0   !*.*A*A!1"&//'+';';*.*A*A)-)?)?-1-G-G		  ,//#'!22<	  0   &,,$t/D/DKi - I (..(43H3HOo / Km 1t 	''%-!+!*G 	 	
" */& 4::/00JJ%%doo6t]++ j 
 $$%%66AAQF4KhKh  I  >>!&&$*G*G s  ((!24>>4CSCS!T!%!1!1!?!?`d!?!e%$2B2BC&$*E*E >>yVZV_V_VrVr>s"@@Z^ZcZcZvZv@wYY 13FGQO
__.q!t45u7G7GH[\]_`\`Ha7bcij
 &:>BBNN""$**,fjjl.@.@.B
 hhnn!!#))+113U__EVWXZ[W[E\5]5a5a5c5i5i5k
 ##%++-335u7G7GH[\]_`\`Ha7b7f7f7h7n7n7p
 	>{m<XeWfgh} 10s   /Hw
w$c                 H    U R                   S L=(       a    U R                  S L$ r  )r  r  r[   s    r`   match_underlying_distribution0_UnslothBCOTrainer.match_underlying_distribution  s$    ""$.W43K3KSW3WWrc   prompt_embeddingsr   c                    UR                   nUR                  nU R                  R                  nU R                  R	                  XR
                  R                  S9nUR                  S   nUR                  SS9U R
                  R                  :g  nU R                  R                  U5      nUR                  S   S:X  a  [        R                  " / X2S9$ U R                  R                  UR                  5       R                  5       R!                  5       5      SS2S4   n[        R"                  " XUS9nU R                  R%                  USS	9nXU-  XdS-   -   nX   nU$ )
z
Calculates the probability if the given prompt embedding is from desirable dataset. This function calculates
the probability in the process and ensemble across processes.
)	pad_indexr   rt   rs   )r   r  Nr  r   mean)	reduction)r  r   r  process_indexpad_across_processesr  r   rw   r  r{   rK   r   r  predict_probar  r  r  	as_tensorreduce)	r[   r  r  r   rankpadded_prompt_embeddingsr  nonzeroprobs	            r`   _get_chosen_prob#_UnslothBCOTrainer._get_chosen_prob  sR   
 "''"))--#'#3#3#H#H)A)A)N)N $I $
  /44Q7*//A/6$:R:R:_:__ ,,334LM ""1%*<<6??xx%%&7&;&;&=&C&C&E&K&K&MNqRStTt@&&tv&>$&q)AB}rc   r   attention_maskc                 
   [         R                  " XR                  R                  :H  U R                  R                  U5      n[         R
                  " 5          U R                  UUS9nSSS5        U$ ! , (       d  f       W$ = f)zl
Replaces processing_class.pad_token_id to embedding_tokenizer.pad_token_id and applies self.embedding_func
r   r  N)rK   wherer  r   r  no_gradr  )r[   r   r  r  s       r`   _vectorize_prompt$_UnslothBCOTrainer._vectorize_prompt  sy     KK..;;;$$11
	 ]]_,,#- - J   _ s   A33
Bbatchc                 8   U R                   (       d  gU R                  US   US   S9n[        R                  " US   [        R                  UR
                  S9n[        R                  " U5      S   n[        R                  " U) 5      S   nX$S4   nX%S4   nXg4$ )	z.Extract embeddings from frozen embedding modelNNembedding_input_idsembedding_attention_maskr  r  r  r   .)r  r
  rK   r   boolr   r  )r[   r  r  r  
chosen_idxrejected_idxr  r  s           r`   _get_prompt_embeddings)_UnslothBCOTrainer._get_prompt_embeddings  s    
 11++12 !;< , 


 eGnEJJzGXGXY[[(+
{{F7+A.&37(s):;!77rc   datasetr  c                    [        [        U5      U5      n[        R                  R	                  [        U5      U4S9nUR                  U5      nU R                  R                  U R                  U R                  R                  U R                  R                  SS.nU R                  R                  [        U40 UD65      n[        R                  " 5          [        R                   " S5      n[#        USS9 HY  n	U R%                  U	S   U	S   S	9n
U R                  R'                  U
5      n
[        R(                  " XR+                  5       45      nM[     S
S
S
5        U$ ! , (       d  f       W$ = f)zf
Sample instances from dataset and get prompt embeddings. Used for density ratio classifier training.
)sizeFr   
collate_fnnum_workers
pin_memoryshuffler   z!Building sample prompt embeddingsiterabler  r  r  r  N)rU  lenr@   rH   choiceselectr\   r   r  r   r  r  preparer   rK   r	  emptyrL   r
  gather_for_metricsr  r  )r[   r  r  	n_samplesrand_indicesembedding_datasetdataloader_paramsdata_loaderall_embeddingspadded_batchr  s              r`   r  0_UnslothBCOTrainer._get_sample_prompt_embeddings-  s@    Gk2	yy''GI<'H#NN<8 ))??,,99;;))99
 &&..z:K/aO`/ab]]_"[[^N $k@c d!33*+@A#/0J#K 4 
 "--@@L
!&NNN<L+M!N !e   _ s   A>E
E.c                   > Ub  UOU R                   R                  n[        TU ]  U5        U R                  R
                  (       a  U R                  R                  [        R                  R                  U[        5      5        U R                  (       aC  [        R                  " U R                  [        R                  R                  U[         5      SS9  g g g )NT)compress)r\   r   rW  _save_optimizer_and_schedulerr  is_main_processr  save_to_jsonrB   pathjoinr!   r  r8   dumpr  r   )r[   r   rY  s     r`   r0  0_UnslothBCOTrainer._save_optimizer_and_schedulerM  s    #-#9Ztyy?S?S
-j9++LL%%bggll:|&LM11DHHbggll:x&HSWX 2	 ,rc   c                 &  > Uc  [         R                  " SU 35        g [        TU ]  U5        [        R
                  R                  U[        5      n[        R
                  R                  U5      (       a&  [        R                  " U R                  U5      U l        U R                  (       ae  [        R
                  R                  U[        5      n[        R
                  R                  U5      (       a  [        R                   " U5      U l        g g g )NzMissing Checkpoint )r:   warning_oncerW  _load_optimizer_and_schedulerrB   r3  r4  r!   isfiler"   load_from_jsonr  r  r  r   r8   loadr  )r[   
checkpointrunning_fileclf_filerY  s       r`   r9  0_UnslothBCOTrainer._load_optimizer_and_schedulerX  s    "5j\ BC-j9 ww||J=77>>,'')889I9I<XDL--ww||J9Hww~~h''!;;x0 ( .rc   c              #     #    U R                   (       aD  U R                  (       d3  U R                  R                  U R                  5      R                  5       O	[        5          U R                  (       a%  U R                  R                  U R                  5        Sv   U R                  (       a.  U R                  R                  U R                  =(       d    S5        SSS5        g! , (       d  f       g= f7f)zWContext manager for handling null reference model (that is, peft adapter manipulation).Nr   )	r  r  r  unwrap_modelrW   disable_adapterrA   set_adapterr  r  s    r`   null_ref_context#_UnslothBCOTrainer.null_ref_contexti  s     
 !!$*?*? ))$**5EEG $$

&&t'<'<=$$

&&t'>'>'K)L  s   A C6"A:C%	C6%
C3/C6c                   > U R                   (       GaC  U R                  (       Gd1  U R                  R                  U R                  U R                  R
                  U R                  R                  SS.nU R                  R                  [        U R                  40 UD65      n/ n[        USS9 HN  nU R                  U5      nU R                  R                  U5      nUR                  UR                  5       5        MP     U R                  R!                  S["        R$                  " U5      R'                  5       R)                  5       S9U l
        SU l        [*        TU ]Y  5       $ )z
Returns the training [`~torch.utils.data.DataLoader`].

Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
Fr  z!Train dataset reference log probsr  reference_logpsnamecolumnT)rK  r  r\   r   r  r   r  r  r#  r   r}  rL   compute_reference_log_probsr%  r   r  
add_columnrK   r  r  r  rW  get_train_dataloader)r[   r)  r*  reference_completion_logpsr,  reference_completion_logprY  s         r`   rN  '_UnslothBCOTrainer.get_train_dataloaderw  s3    (((1V1V1V"iiCC"00#yy??"ii== ! **22:d>P>P3fTe3fgK)+& $k@c d,0,L,L\,Z),0,<,<,O,OPi,j)*112K2O2O2QR	 !e "&!3!3!>!>&uyy9S/T/Z/Z/\/b/b/d "? "D 59D1w+--rc   c                   > Uc  U R                   c  [        S5      eUb  UOU R                   nU R                  (       Ga=  U R                  (       Gd+  U R                  R
                  U R                  U R                  R                  U R                  R                  SS.nU R                  R                  [        U40 UD65      n/ n[        USS9 HN  nU R                  U5      nU R                  R                  U5      nUR                  UR!                  5       5        MP     UR#                  S[$        R&                  " U5      R)                  5       R+                  5       S9nU R                   b  Xl         SU l        [,        TU ]]  US	9$ )
a  
Returns the evaluation [`~torch.utils.data.DataLoader`].

Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.

Args:
    eval_dataset (`torch.utils.data.Dataset`, *optional*):
        If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
        by the `model.forward()` method are automatically removed. It must implement `__len__`.
z-Trainer: evaluation requires an eval_dataset.Fr  z Eval dataset reference log probsr  rH  rI  T)r~  )r~  r   rK  r  r\   r   r  r   r  r  r#  r   rL   rL  r%  r   r  rM  rK   r  r  r  rW  get_eval_dataloader)r[   r~  r)  r*  rO  r,  rP  rY  s          r`   rS  &_UnslothBCOTrainer.get_eval_dataloader  sj    D$5$5$=LMM'3'?|TEVEV(((1U1U1U"iiBB"00#yy??"ii== ! **22:l3`N_3`aK)+& $k@b c,0,L,L\,Z),0,<,<,O,OPi,j)*112K2O2O2QR	 !d (22&uyy9S/T/Z/Z/\/b/b/d 3 L
   ,$0!37D0w**EErc   r,  c           	         [         R                  " 5          U R                  c  U R                  5          U R                  (       a5  U R                  US   US   UR                  S5      US   S9R                  nO U R                  US   US   S	9R                  nSSS5        OfU R                  (       a5  U R                  US   US   UR                  S5      US   S9R                  nO U R                  US   US   S	9R                  nSSS5        U R                  WUS   S
U R                  U R                  S9nU$ ! , (       d  f       NB= f! , (       d  f       NK= f)zfComputes log probabilities of the reference model for a single padded batch of a BCO specific dataset.Nprompt_input_idsprompt_attention_maskcompletion_decoder_input_idscompletion_labels)r  decoder_input_idsr  r   completion_attention_mask)r  Faverage_log_probrJ  rE  )
rK   r	  r|  rE  rJ  rW   r  r   get_batch_logpsrE  )r[   r,  completion_logitscompletion_logpss       r`   rL  ._UnslothBCOTrainer.compute_reference_log_probs  s   ]]_~~%**,..,0JJ();<+78O+P.:.>.>?].^#/0C#D	 -7 -
 !& * -1JJ()?@+78S+T -7 - !& * -,  **(,$%78'34K'L*6*:*:;Y*Z+,?@	 )7 )
 f & )-$%;<\ZuMv )7 )f &7 >  //,-"#66#66 0 
  K -, _s$   EA'D>A/E>
E	E
Er   r  r]  rE  rJ  c                 z   U R                   SS UR                   :w  a  [        S5      eU(       d(  USS2SS24   R                  5       nU SS2SS2SS24   n OUR                  5       nX:g  nSXU:H  '   [        X5      nU(       a%  Xe-  R	                  S5      UR	                  S5      -  $ Xe-  R	                  S5      $ )aJ  Compute the log probabilities of the given labels under the given logits.

Args:
    logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
    labels:
        Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are
        ignored. Shape: (batch_size, sequence_length)
    average_log_prob:
        If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
        log probabilities of the (non-masked) tokens.
    label_pad_token_id:
        The label value to ignore when computing log probabilities.
    is_encoder_decoder:
        Whether the model is an encoder-decoder model. If True, the labels are not shifted, and the logits are
        assumed to already be aligned with the labels. If False, the labels are shifted to the right by one
        position, and the logits are assumed to be aligned with the shifted labels.

Returns:
    A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
    given logits.
Nrn   zKLogits (batch and sequence length dim) and labels must have the same shape.rt   r   )rw   r   clonerI   r   )r   r  r]  rE  rJ  	loss_maskr   s          r`   r^  "_UnslothBCOTrainer.get_batch_logps  s    : <<,jkk!AqrE]((*FAssAI&F \\^F0	 01++,/?#/44R89==;LLL#/44R88rc   c                    U R                   (       a  US   UR                  S5      S.O0 nU R                  (       a  SUS'   U" US   4SUS   0UD6nUR                  nU R	                  UUS   S	U R                   U R
                  S
9nUR                  S   [        US   5      :w  a  [        S5      e[        UR                  S   5       Vs/ s H  orS   U   SL d  M  UPM     nn[        UR                  S   5       Vs/ s H  orS   U   S	L d  M  UPM     n	nXhS4   n
XiS4   nXXS4   nXYS4   nU R                  (       a  XXUR                  4$ XX4$ s  snf s  snf )NrY  rX  )r  rZ  Tr  r   r  r[  Fr\  r   r  zThere is a mismatch between the number of examples in this batch and the number of examples for which an output sequence was predicted..)rJ  r  r  r   r^  rE  rw   r   r   rangeaux_loss)r[   rW   r  model_kwargsoutputsr_  r`  ir  r  chosen_logpsrejected_logpschosen_logitsrejected_logitss                 r`   forward_UnslothBCOTrainer.forward%  s    &&   34%*YY/M%N
  	   37L/0()
 !<=
 

 $NN//%&"#66#66 0 
 !!!$E'N(;;G 
 "''7'='=a'@!A_!AA7^TUEVZ^E^a!A
_#()9)?)?)B#Cb#CaW~VWGX\aGa#Cb'C8)*;<)c/:+#,=>   -RYRbRbcc -QQ `bs   EE EEr  c                     U R                  U5      nU R                  R                  nU R                  R                  nUSU-
  S-   -  R	                  X4S9nU$ )Nrt   r\  )rU  rV  )r  r\   rP  rQ  clamp)r[   r  prob_desirable	min_ratio	max_ratioweights         r`   _get_udm_weight"_UnslothBCOTrainer._get_udm_weightV  sX    ../BCII//	II//	 A$6$=>EE)Ecrc   policy_chosen_logpspolicy_rejected_logpsreference_chosen_logpsreference_rejected_logpsr  r   c                    X-
  nU R                   U-  n	X$-
  n
U R                   U
-  nU(       a?  U R                  R                  [        R                  " X4S5      R                  5       5        [        R                  " U R                  R                  U	R                  S9n[        R                  " X-
  5      * n[        R                  " X-
  * 5      * nU R                  (       aD  [        R                  " U5      nU R                  U5      n[        R                  " X-  UU-  4SS9nO[        R                  " X4SS9nUXU4$ )a  Compute the BCO loss for a batch of policy and reference model log probabilities.

Args:
    policy_chosen_logps:
        Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,)
    policy_rejected_logps:
        Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,)
    reference_chosen_logps:
        Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,)
    reference_rejected_logps:
        Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in
        batch_size,)
    chosen_embeddings: embeddings of desirable prompts
    rejected_embeddings: embeddings of undesirable prompts
    do_train: whether to update the running delta value. Default is True.

Returns:
    A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, delta). The losses tensor contains the
    BCO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards
    for the chosen and rejected responses, respectively. The delta value contains the moving average of all
    implicit rewards.
r   r   rs   )rD  r  updaterK   r  detachr  r  r   r   
logsigmoidr  r  rx  )r[   rz  r{  r|  r}  r  r  r   chosen_logratioschosen_rewardsrejected_logratiosrejected_rewardsdeltachosen_lossesrejected_losseschosen_weightrejected_weightlossess                     r`   bco_loss_UnslothBCOTrainer.bco_loss_  s   B /G%552M99'99LL		>*La P W W YZ 1 1.:O:OPn&<==<<*:*B(CDD--!OOM:M"223FGOYY =Q`?`aghiFYY?QGF~>>rc   c           
      
   0 nUR                  5        VVs0 s HL  u  pVU[        U[        R                  5      (       a%  UR	                  U R
                  R                  5      OU_MN     nnnU R                  X5      nUSS u  nn	n
nU R                  (       a  US   nSU;   a  [        US   R                  S   5       Vs/ s H  oS   U   SL d  M  UPM     nn[        US   R                  S   5       Vs/ s H  oS   U   SL d  M  UPM     nnUS   US4   nUS   US4   nO[        R                  " 5          U R                  c>  U R                  5          U R                  U R                  U5      SS u  nnnnSSS5        O$U R                  U R                  U5      SS u  nnnnSSS5        U R                  U5      u  nnU R!                  UU	WWUUUS	9u  nnnnU R
                  R#                  U5      R%                  5       R'                  5       US
'   [        R                  " [)        U5      /5      R	                  U R
                  R                  5      n[        R                  " [)        U5      /5      R	                  U R
                  R                  5      nU R
                  R#                  U5      R+                  5       R'                  5       nU R
                  R#                  U5      R+                  5       R'                  5       nUS:  a  U R
                  R#                  UR-                  5       5      R-                  5       R'                  5       US'   U R
                  R#                  UR-                  5       5      R-                  5       R'                  5       US'   U R
                  R#                  U
R-                  5       5      R-                  5       R'                  5       US'   UUS'   US:  a  U R
                  R#                  UR-                  5       5      R-                  5       R'                  5       US'   U R
                  R#                  U	R-                  5       5      R-                  5       R'                  5       US'   U R
                  R#                  UR-                  5       5      R-                  5       R'                  5       US'   UUS'   UR/                  5       nU R                  (       a  UU R0                  W-  -  nUU4$ s  snnf s  snf s  snf ! , (       d  f       GN= f! , (       d  f       GN= f)zWCompute the BCO loss and other metrics for the given batch of inputs for train or test.Nro   rH  r   r  TF.r   r  zrewards/chosen_sumzlogps/chosen_sumlogits/chosen_sumzcount/chosenzrewards/rejected_sumzlogps/rejected_sumlogits/rejected_sumzcount/rejected)itemsr  rK   r   ry   r  r   rp  r  rg  rw   r	  r|  rE  rW   r  r  r%  r  itemr   r   nansumnanmeanr  )r[   rW   r  r   metricskvforward_outputrz  r{  policy_chosen_logitspolicy_rejected_logitsrh  rk  r  r  r|  r}  _r  r  r  r  r  r  
num_chosennum_rejectedall_num_chosenall_num_rejectedlosss                                 r`   get_batch_loss_metrics)_UnslothBCOTrainer.get_batch_loss_metrics  s    fkfqfqfstfs^b^_jELL6Q6QQTT$**112WXXfste3 2A	
! "  %a(H %%*51B+C+I+I!+L%Mk%MW^Q_`aQbfjQj!%MJk',U3D-E-K-KA-N'On'O!Y`SabcSdhmSmA'OLn%*+<%=j#o%N"',->'?c@Q'R$>>)..0 !LLU;BQ?24 10 T^^U;BQ?.0 !" 261L1LU1S..:>--!"$ ;H ;
7 0%  ++>>uEJJLQQS\\3~#6"78;;D<L<L<S<ST
||S)9%:$;<??@P@P@W@WX))<<ZHLLNSSU++>>|LPPRWWYA  33N4I4I4KLSSUZZ\ ()   334G4N4N4PQXXZ__a &'   334H4O4O4QRYY[``b '( '5GN#a  334D4K4K4MNUUW\\^ *+   334I4P4P4RSZZ\aac ()   334J4Q4Q4ST[[]bbd )* )9G$%~~  D&&11DW}i u ln 10 !sB   AT TT7T	T;T.%T>-T.
T+	&T..
T=inputsc                    U R                   (       a)  [        U R                  R                  R                  5      O	[        5       nU   U R                  X5      u  pgS S S 5        WR                  U R                  R                  5      nU R                  R                  (       a  U R                  WSS9  U(       a  UW4$ U$ ! , (       d  f       Nk= f)Ntrain
train_eval)r  r)   r  r   r  rA   r  ry   r\   r1  store_metrics)r[   rW   r  return_outputsnum_items_in_batchcompute_loss_context_managerr  r  s           r`   compute_loss_UnslothBCOTrainer.compute_loss  s     7;6X6XHT%%,,112^i^k 	% * 77FMD * wwtyy''(++w7;'?" *)s   C  
Cr  r  )r  evalc                 x    UR                  5        H&  u  p4U R                  U   U   R                  U5        M(     g r  )r  r  r   )r[   r  r  keyvalues        r`   r   _UnslothBCOTrainer.store_metrics  s2    !--/JC  ,S188? *rc   c                 ^    Uc  U R                   nUb  [        U5      (       d  g [        U5      $ r  )r}  r0   r#   )r[   r  s     r`   _get_train_sampler%_UnslothBCOTrainer._get_train_sampler  s/    ?((G?*W"5"5 ))rc   c           
         U R                   (       a)  [        U R                  R                  R                  5      O	[        5       nU   UR                  US   US   U R                  SU R                  R                  S9nSU;   a  US   nOU R                  c[  U R                  5          U R                  R                  US   US   U R                  SU R                  R                  S9nSSS5        OAU R                  R                  US   US   U R                  SU R                  R                  S9nSSS5        [        WU R                  U R                  R                  5      nU R                  R                  USS9n[        WU R                  U R                  R                  5      nU R                  R                  USS9nXg4$ ! , (       d  f       N= f! , (       d  f       N= f)zRGenerate samples from the model and reference model for the given batch of inputs.rV  rW  T)r   r  rA  	do_sampler   reference_outputN)skip_special_tokens)r  r)   r  r   r  rA   generaterA  r  r   r|  rE  rW   rC   batch_decode)r[   rW   r  generate_context_managerpolicy_outputr  policy_output_decodedreference_output_decodeds           r`   generate_from_model_and_ref._UnslothBCOTrainer.generate_from_model_and_ref  s    7;6X6XHT%%,,112^i^k 	! &!NN 23$%<=??!22?? + M "U*#();#< >>)..0+/::+>+>&+,>&?+01H+I'+&*)-)>)>)K)K ,? ,( 10 (,~~'>'>"'(:";',-D'E#'??"&%)%:%:%G%G (? ($/ &> &mT__dF[F[FhFhi $ 5 5 B B=fj B k()94??DLaLaLnLno#'#8#8#E#EFVlp#E#q $>>/ 10 &%s'   A!G(AG	*A
G	
G	G
G(r   ignore_keysc                    Uc+  [        US5      (       a  [        UR                  S/ 5      nO/ nU R                  (       a)  [	        U R
                  R                  R                  5      O	[        5       n[        R                  " 5          U   U R                  XSS9u  pgS S S 5        S S S 5        U R
                  R                  (       a  U R                  WSS9  U(       a  WR                  5       S S 4$ 0 nSW;   a  US   US'   S	U;   a  US	   US
'   UR                  5        V	V
s/ s H  u  pX;  d  M  U
PM     nn	n
[        R                   " XR
                  R                  S9n[        R"                  " UR$                  S   U R
                  R                  S9nWR                  5       X4$ ! , (       d  f       GN= f! , (       d  f       GN= fs  sn
n	f )Nr  keys_to_ignore_at_inferenceFr  r  r  r  zeval_logits/chosenr  zeval_logits/rejectedr   r   )rZ   r  r  r  r)   r  r   r  rA   rK   r	  r  r1  r  r  r  r   zerosrw   )r[   rW   r  r   r  prediction_context_managerr  r  logits_dictr  r  r   r  s                r`   prediction_step"_UnslothBCOTrainer.prediction_stepG  s    uh''%ell4QSUV  7;6X6XHT%%,,112^i^k 	# ]]_8 77PU7VMD 9_ ++w6:KKM4.. ')078K0LK,- G+29:O2PK./ + 1 1 3L 3q7K! 3Lf-=-=-D-DEV\\!_T5E5E5L5LMv..) 98__  Ms0   F>F,F>$G3G,
F;	6F>>
G
dataloaderdescriptionmetric_key_prefixc                   > U R                   (       Ga  [        UR                  5      n[        R                  " [        U5      U R                  R                  S9nUR                  R                  U5      nU R                  U5      n	U R                  U	5      n	[        R                  " U	S   [        R                  U R                  R                  S9n
[        R                   " U
) 5      S   nU	S   U   U	S   U   [#        U6 " U	S   5      S.nU R%                  U R&                  U5      u  p[(        R*                  " / S	Q[-        US   X5       VVVs/ s H$  u  nnnUU[        U5      S
 U[        U5      S
 /PM&     snnnS9nSU R                  R.                  ;   a(  [0        R3                  S[0        R5                  US905        SU R                  R.                  ;   a
  [7        SUS9  [8        TU ]u  XX4U5      nU$ s  snnnf )z
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
`Trainer.evaluate()` and `Trainer.predict()`.

Works both with or without labels.
)r  r  r  r   rV  rW  prompt)rV  rW  r  )PromptPolicyz	Ref ModelN)columnsdatawandbgame_log)r  comet_mlzgame_log.csv)rJ  table)rI  r   r  rH   samplerg  r\   eval_batch_sizer"  r  _prepare_inputsrK   r   r  r  r   r  r7   r  rW   rD   	DataFramerx   r  r  logTabler9   rW  evaluation_loop)r[   r  r  r   r  r  num_samplesrandom_indicesrandom_batch_datasetrandom_batchtarget_labelstarget_indicestarget_batchr  ref_output_decodedr  polrefr  initial_outputrY  s                       r`   r  "_UnslothBCOTrainer.evaluation_loopm  s     $$$j001K#]]5+=AZAZ[N $.#5#5#<#<^#L --.BCL//=L!LLg)>ejjY]YiYiYpYpqM"[[-8;N$01C$D^$T)56M)N~)^$n5l86LML
 9=8X8XY]YcYceq8r5!LL9 -0X0FH],r,r(S SV/S[]1CD,rE $))---		:u{{{'>?@TYY000-' 0%9HY
 's   +G=logs
start_timec           	      D  > SU;   a  SOSnUS:X  a  SOSnS H  nSU 3U R                   U   ;   d  M  [        R                  " U R                   U   SU 3   5      R                  5       R	                  5       nS Hm  n[        R                  " U R                   U   U S	U S
3   5      R                  5       R	                  5       U-  X U S	U 3'   U R                   U   U S	U S
3	 Mo     U R                   U   SU 3	 M     U S3U;   a  U S3U;   a  X S3   X S3   -
  X S3'   U R                   U   R                  5        H=  u  p[        R                  " U	5      R                  5       R	                  5       X U 3'   M?     U R                   U	 [        T
U ]!  X5      $ )z
Log `logs` on the various objects watching training, including stored metrics.

Args:
    logs (`dict[str, float]`):
        The values to log.
    start_time (`float` or `None`, *optional*, defaults to `None`):
        Start time of the training.
r  r  r  eval_rd  )chosenrejectedzcount/)rewardslogpsr   /_sumzrewards/chosenzrewards/rejectedzrewards/margins)	r  rK   r   r   r  r  r  rW  r  )r[   r  r  r  r  split	count_summetricr  r  rY  s             r`   r  _UnslothBCOTrainer.log  s    !'$WF
&&0b+Ew4#7#7
#CC!LL)=)=j)IFSXRYJZ)[\``bggi	<FT%9%9*%EPQRWQXX\F]%^_ccejjl#$ 8F81UG45
 ,,Z8F81UG49PQ = ((4veW5EF , X^$,F8;K1LPT1T/3hn4M/NQUX``pVqQr/rD8?+, 00<BBDLC%*\\'%:%?%?%A%F%F%HD8C5!" E  ,w{4,,rc   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 )Nr  rn   )
model_name)	r\   r   r   r   rJ  r  create_model_cardrW  _save_checkpoint)r[   rW   trialr  rY  s       r`   r  #_UnslothBCOTrainer._save_checkpoint  sj    99!!)dii22388J//55c:2>J*5 .rc   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        [        R                   " S5      n[#        UUU R$                  UU['        5       (       a+  [(        R*                  b  [(        R*                  R,                  OS[/        5       SUS	S
S9nUR1                  [        R
                  R3                  U R4                  R6                  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_jobsaA          @article{jung2024binary,
            title        = {{Binary Classifier Optimization for Large Language Model Alignment}},
            author       = {Seungjae Jung and Gunsoo Han and Daniel Wontae Nam and Kyoung{-}Woon On},
            year         = 2024,
            eprint       = {arXiv:2404.04656}
        }BCOzABinary Classifier Optimization for Large Language Model Alignmentz
2404.04656)
base_modelr  r   r  r   	wandb_url	comet_urltrainer_nametrainer_citationpaper_titlepaper_idz	README.md)is_world_process_zerorZ   rW   r  rB   r3  isdirr  setr  r  addenvironr  r  rJ   dedentr.   r   r6   r  runurlr/   saver4  r\   r   )r[   r  r  r   r  citation
model_cards          r`   r  $_UnslothBCOTrainer.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Hrc   )r  r  r  r  r  r  rD  r  r  r  r~  rI  rJ  r  rE  rC  rA  rB  r  r  rF  rK  r  r|  r  r}  rG  r  )NNNNNNNNNr  NNNNNNN)rk  r  )Frl  F)T)FNr  )NNr  )NNN)Irn  ro  rp  rq  rr  r  r	   r   r?   Moduler  r   r   r   dictr   r   r   r    r   r   r  r%   tuplerK   r  	Optimizerlr_schedulerLambdaLRr   r   rX  propertyr  FloatTensorr  
LongTensorr
  r  rt  r  r0  r9  r*   rE  r   rN  rS  rL  staticmethodr  r^  rp  rx  r  r  r   r  r  r   r  utilsr  Samplerr  r  r  r  r  r  r  ru  rv  rw  s   @r`   ry  ry    s]   +Z J 9=FJ+/EI 04>B59Vbhl&*FJ,0*.-1AE)bi_bii45bi E/299c"ABCbi 	bi
  (bi uWd3<.@%@ABbi #)+=?UWeef
bi  -bi Xb/&9:;bi D12bi %++//1I1I1R1RRSbi (0%,,9UW\WcWc9c0d'ebi d^bi  "(N+;T+A"BC!bi" %SM#bi$ #3-%bi& !*'bi( &&=>)bi biH X X%2C2C HYHY :5+;+; UM]M] bgbsbs $8#uT5+;+;%;<<=8	u  %"3"33	48,W 3 Y^YjYj @	Y1" M M .j  .D,F0A ,FZ ,F ,F\)  )  ) V  "'"&#(09!!09  09 09  	09
 !09 
		09 09d/RYY/R'+CtU=M=M7M1N,N'O/R	u  %"3"3U5F5FHYHYY	Z/Rb53D3D IZIZ " 6?"..6?  %006? !& 1 1	6?
 #("3"36? $E$5$566? &e&7&786? 6? 
u  %"3"3U5F5FHYHYY	Z6?x 	\ CtU%5%55667\ 	\D _bii/0 S%c 1223 
u||U5<<c5<<6G1H#HII	J0@T#u*%5 @7?C[ @jn @*(7*; *xPUP[P[P`P`PhPhGi *-?S%BRBR=R8S -?X]^acf^fXg -?h ,0$/_bii/0$/ S%c 1223$/ #	$/
 d3i($/T 04+/!'88 8 'tn	8
 d3i(8 8 
8 8t!-S%Z( !-huo !-QU !- !-H/ %)&*,0	@ISM@I sm@I CcD()	@I @Irc   ry  c                   P   ^  \ rS rSrSr                SU 4S jjrSrU =r$ )UnslothBCOTraineri  a4  
    
Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper.

Args:
    model (`transformers.PreTrainedModel`):
        The model to train, preferably an `AutoModelForSequenceClassification`.
    ref_model (`PreTrainedModelWrapper`):
        Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
        and loss. If no reference model is provided, the trainer will create a reference model with the same
        architecture as the model to be optimized.
    args (`BCOConfig`):
        The arguments to use for training.
    train_dataset (`datasets.Dataset`):
        The dataset to use for training.
    eval_dataset (`datasets.Dataset`):
        The dataset to use for evaluation.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*, defaults to `None`):
        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.
    data_collator (`transformers.DataCollator`, *optional*, defaults to `None`):
        The data collator to use for training. If None is specified, the default data collator
        (`DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the
        sequences in the batch, given a dataset of paired sequences.
    model_init (`Callable[[], transformers.PreTrainedModel]`):
        The model initializer to use for training. If None is specified, the default model initializer will be
        used.
    callbacks (`list[transformers.TrainerCallback]`):
        The callbacks to use for training.
    optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
        The optimizer and scheduler to use for training.
    preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
        The function to use to preprocess the logits before computing the metrics.
    peft_config (`dict`, defaults to `None`):
        The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
        a PEFT model.
    compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
        The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
        metric values.
    model_adapter_name (`str`, defaults to `None`):
        Name of the train target PEFT adapter, when using LoRA with multiple adapters.
    ref_adapter_name (`str`, defaults to `None`):
        Name of the reference PEFT adapter, when using LoRA with multiple adapters.

    c           
      x  > 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 ]  " SN0 S=U_S>U_S?U_S@U_SU_S,U_SAU_SBU_SCU	_S%U
_SDU_S$U_SEU_SFU_SGU_SHU_UD6  S=[9        5       ;   a!  [;        USI5      (       a  URg                  5         [;        U SJ5      (       a-  U Rh                  Rk                  5         [;        U SJ5      (       a  U ?4[        USKS 5      b  U Rl                  UR                  5       l6         [;        U SL5      (       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 SM5      (       a.  [w        [y        U Rz                  R|                  5      U 5      U l>        g )ONr   Fr   UNSLOTH_ENABLE_FULL_FINETUNING01UNSLOTH_FORCE_FLOAT32zKUnsloth: Switching to float32 training since model cannot work with float16TUNSLOTH_MIXED_PRECISIONrz   r  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_PRECISIONr~  r   r   r   r^  r   rt   )__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   bfloat16r  r  UNSLOTH_RETURN_LOGITSr   rX   r  padding_siderightr  )UnslothVisionDataCollatorr  re  pad_to_multiple_of)mlmmlm_probabilityr:  )r:  r  dataset_text_fieldrd  dataset_kwargsskip_prepare_datasetpad)PatchRLStatisticsbco_trainerparallel_mode_n_gpurW   r|  r\   r}  r  r  r  r  r  r  r  r  rY   neftune_hook_handler9  r  r  rR  )?r   r  r  r  rB   r  r  rS  r  r  r  unsloth_zoo.utilsr1  rK   float16	TypeErrorr   r   r   r   transformersr3  rP   r   r   r   r   r   localsrZ   r   rX   r  r7  unsloth_zoo.vision_utilsr9  r  rQ   column_names+TransformersDataCollatorForLanguageModelingr  r=  r>  unsloth_zoo.logging_utilsrA  rS   NOT_DISTRIBUTEDn_gpurD  rW  rX  rY   rE  remover9  r  scaleraccelerator_scalerrW   rT   rf   rY  r  )*r[   rW   r|  r\   r}  r~  r  r  r  r  r  r  r  r  r  r  r  r]   use_bf16use_fp16force_float32full_finetuningmixed_precision_dtyper  r1  rG  ga_stepstransformers_versioneval_bszr   r   _output_logitsmodel_max_seq_lengthargs_max_seq_lengthr   _UnslothBCOTrainer__tokenizerr9  other_metricsrA  rR  current_modelrY  s*                                            r`   rX  UnslothBCOTrainer.__init__C  s<   ( < 0 2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 ?-7 4$/<3O3OOTXT^T^abTbtXq)Q.fh75.#A#A  	@	@!	@ 	@ *		@
 (	@  0	@ *	@ $	@ "	@ -J	@ &	@ .	@ "4	@  0	@ ,	@  #6!	@" 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rc   r  )NNNNNNNNNNNNNNNN)rn  ro  rp  rq  rr  rX  ru  rv  rw  s   @r`   r)  r)    sG    -` (,!"#o orc   r)  	addFilterc                        \ rS rSrS rS rSrg)HideLoggingMessagei  c                     Xl         g r  text)r[   rh  s     r`   rX  HideLoggingMessage.__init__  s    d)rc   c                 <    U R                   UR                  5       ;  $ r  )rh  
getMessage)r[   r  s     r`   r  HideLoggingMessage.filter  s    alln)DErc   rg  N)rn  ro  rp  rq  rX  r  ru  rR  rc   r`   re  re    s    2Erc   re  z`use_cache=True`)mrr  rK   r   torch.nnr?   r   r   typingr   r   r   r   r	   r
   r   r   trl.trainer.bco_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   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rL   dataclassesrN   rO   packaging.versionrP   r  
contextlibrI  rQ   rR   rM  transformers.training_argsrS   rd   typesrT   rf   torch_compile_optionscompiler   rt  r   r   r   r   ry  r)  rZ   Filterre  rc  rR  rc   r`   <module>rx     s&  0    $ I I I N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N 
  ( %   " $  3      4;PR S"||  \\	&,, %  	
 \\6ell C ELL  ~-y ~- ~-~ CI CIH(^* ^@  6;FW^^ F 	
'(:;<  rc   