
    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  SSK&r&SSK7  SSK)J*r*J+r+  SS	K,J-r-  SSKrSSK.r/SS
K0J1r1  SSKJr  SSK2J3r3J4r5  SSK6J7r7  SSK8r8SSK9J:r:  S r; SSSSSS.r<\Rz                  " SS\<S9S 5       r>S\R                  S\?S\?S\R                  4S jr@S\R                  S\R                  S\?S\?S\R                  4
S jrAS\R                  S\?S\R                  4S jrB\* " S  S!\5      5       rC  " S" S#\5      rD " S$ S%\D5      rEg)&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)"BaseImageProcessorr   DataCollator"DataCollatorForTokenClassificationDatasetEvalPredictionFeatureExtractionMixinr   	PRMConfig
PRMTrainerPartialStatePathPreTrainedModelPreTrainedTokenizerBaseProcessorMixinTrainerTrainerCallbackr	   chaincompute_accuracydisable_dropout_in_modelfeaturesgenerate_model_cardis_wandb_availablennosprepare_peft_modeltextwraptorchr   r   r   r#   r&   )*)	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)hasattrr2   r3   r4   )selfargskwargsoutputfs       >/home/james-whalen/unsloth_compiled_cache/UnslothPRMTrainer.pywrapper*prepare_for_training_mode.<locals>.wrapper0   sx     4!!gdjj.&I&IJJ##%4)$)&)4!!gdjj/&J&JJJ$$&    )	functoolswraps)r:   r<   s   ` r;   prepare_for_training_moderA   /   s%    __Q  Nr>   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)rL   indexrL      )r&   chunkreshapeshapeziptofloat32gather	unsqueezesqueeze	logsumexpappendconcat)
logitsrM   chunked_logitschunked_indexall_per_token_logpschunk_logitschunk_indexselected_logitslogsumexp_valuesper_token_logpss
             r;   chunked_selective_log_softmaxre   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r>   	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 
rO   z8logits_to_keep must be smaller than the sequence length.NrN   )rR   
ValueErrorsum)rf   rg   rh   prompt_sectionpadding_maskpad_token_countss         r;   calculate_pad_tokens_in_promptrp   W   sX     ++STTq"2N?"223N"2L#''A'.r>   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   rO   )rR   ru   r&   arangerW   )rq   rr   rs   rh   
batch_sizecompletion_lenru   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r>   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.
rO   T)rL   
descendingstable)r&   argsortrV   )r   r   masksorted_indicespacked_tensors        r;   left_pack_paddingr      s8     D]]4Q4MNLLN;Mr>   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$ )UnslothPRMConfig   a  
    
Configuration class for the [`PRMTrainer`].

This class includes only the parameters that are specific to PRM 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) used for truncation.
    max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
        Maximum length of the prompt used for truncation.
    max_completion_length (`int` or `None`, *optional*, defaults to `None`):
        Maximum length of the completion used for truncation. The completion is the concatenation of the steps.
    disable_dropout (`bool`, *optional*, defaults to `True`):
        Whether to disable dropout in the model.
    step_separator (`str`, *optional*, defaults to `"
"`):
        Separator used to separate each step of the reasoning process.
    train_on_last_step_only (`bool`, *optional*, defaults to `False`):
        Whether to train only on the last step.
    dataset_num_proc (`int`, *optional*, defaults to `None`):
        Number of processes to use for processing the dataset.

    NhelpzvLLM SamplingParams)defaultmetadatavllm_sampling_paramsrI   z8Chunk size to reduce memory usage. -1 is most efficient.unsloth_num_chunksz'Maximum sequence length to truncate to.max_seq_lengthc                 H  > 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_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!rO   za` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!steps  unsloth_training_checkpointsnor   )	cpu_countrJ      @   
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disable_dropoutstep_separatortrain_on_last_step_onlydataset_num_proc )
printmultiprocessingr   minmaxsuper__init__r   r   r   )r6   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!  r   r   r   r8   r   	__class__s                                                                                                                                                 r;   r(  UnslothPRMConfig.__init__   sp   ` 4)I-  YB  (C  "D1e&F}o  Vw  %x  y-7":zS?P7J M#1"3y{1}a#8"= H	:#H	:#7H	:  H	: 	H	:
 $H	: *H	: $8H	: +FH	: *DH	: (@H	: '>H	: +FH	: '>H	: $H	: '>H	:  *!H	:" (#H	:$ $%H	:& $'H	:( ()H	:* *+H	:,  0-H	:. "/H	:0 !21H	:2 (3H	:4 (5H	:6 "7H	:8 !29H	::  0;H	:< &=H	:>  0?H	:@ "4AH	:B *CH	:D &<EH	:F *GH	:H $IH	:J  0KH	:L  0MH	:N !2OH	:P .QH	:R 7^SH	:T UH	:V WH	:X ,YH	:Z [H	:\ "]H	:^ *_H	:`  aH	:b cH	:d eH	:f ,gH	:h &<iH	:j ,kH	:l ,mH	:n oH	:p $qH	:r &sH	:t *uH	:v !2wH	:x yH	:z $8{H	:| $}H	:~ &<H	:@ *DAH	:B $CH	:D  EH	:F (GH	:H %:IH	:J &KH	:L &<MH	:N %:OH	:P !2QH	:R  0SH	:T UH	:V #6WH	:X &YH	:Z 2T[H	:\ "4]H	:^ "4_H	:` "aH	:b &<cH	:d eH	:f $gH	:h "iH	:j .kH	:l "4mH	:n "oH	:p *DqH	:r !2sH	:t %:uH	:v %:wH	:x -JyH	:z #6{H	:| *D}H	:~ &H	:@ &<AH	:B (CH	:D (EH	:F "GH	:H  0IH	:J .KH	:L (MH	:N &<OH	:P -JQH	:R *DSH	:T &<UH	:V (WH	:X $8YH	:Z (@[H	:\ !2]H	:^ *_H	:` $8aH	:b  0cH	:d &eH	:f "gH	:h &iH	:j *kH	:l %:mH	:n "4oH	:p )BqH	:r -JsH	:t #6uH	:v $8wH	:x "4yH	:z *{H	:|  0}H	:~ #6H	:@ &<AH	:B -JCH	:D $EH	:F !2GH	:H %:IH	:J .KH	:L ,MH	:N '>OH	:P  0&QH	:R %9!"4,r>   )r   r   r   )NNFFFr   FrJ   rJ   NNr   r   r      g-C6
?g{Gz?g?g+?g:0yE>g      ?g      @rI   linear皙?r   passivewarningTNr   FrO   Fr   r   NTFFFFFFO  r0  FFFFO1autoFFNrI   NNF FNr   NrI   NNTNFNNFr3  r   NNNNN        
adamw_8bitNFFlengthNNNNTFTFFNN
every_saveNNFNTNFTr2  NNNr3  FFNlasti  FNNFFNNFFFNFTi   i   NTr3  FNNrI   N)__name__
__module____qualname____firstlineno____doc__r)   r   r   r   __annotations__r   intr   r(  __static_attributes____classcell__r)  s   @r;   r   r      s%   : +012+(3-  */VW*#  &+EF&NXc]  #$&'%&#'"&&'"#"%$%""!&!27!'!$!"%) $!& $  -1!!!$%%)  $ $(-"%*!%#!%(,%*!%##' $  $!$)(-"#" "!&(, $"'#[d- d-r>   r   c                   4  ^  \ 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 5       r!U 4S jr"   SS\\   S\\   S\\\\   S4   4S jjr#Sr$U =r%$ )_UnslothPRMTraineri  a  
Initialize PRMTrainer.

Args:
    model (`transformers.PreTrainedModel`):
        The model to train, preferably an `AutoModelForTokenClassification`.
    args (`PRMConfig`):
        The arguments to use for training.
    data_collator (`transformers.DataCollator`):
        The data collator to use for training. If None is specified, the default data collator
        (`DataCollatorForTokenClassification`) 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`):
        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.
    model_init (`Callable[[], transformers.PreTrainedModel]`):
        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 `compute_accuracy`):
        The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`)
        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.
trlprmNr2   r7   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[        XbR                  S9nSUR                  ;  Ga  [        5       R                  5          UUR                  UR                  UR                  UR                  UR                  S.n0 UESS0EnUR                  U R                  UUR                   UR"                  S["        R$                  " ["        R&                  " ["        R(                  " S5      5      ["        R&                  " ["        R(                  " S5      5      S	.5      S
9n0 UESS0EnUb  UR                  U R                  UUR                   UR"                  S["        R$                  " ["        R&                  " ["        R(                  " S5      5      ["        R&                  " ["        R(                  " S5      5      S	.5      S
9nS S S 5        [*        TU ]Y  UUUUUUUUU	U
US9  [/        U R0                  S5      (       a&  U R0                  R3                  U R4                  5        g g ! , (       d  f       Ng= f)NFz^A processing_class must be specified when using the default DataCollatorForTokenClassification)r  rf   )	tokenizerr  r  r  r  r   is_evalzTokenizing train datasetint64)labelsrf   )	fn_kwargsnum_procremove_columnsdescr   TzTokenizing eval dataset)r2   r7   rG  rH  rI  rJ  rK  rL  rM  rN  rO  add_model_tags)r$   r  r   r   rk   r   r  column_namesr   main_process_firstr  r  r  r   maptokenize_rowr!  r   FeaturesSequenceValuer'  r(  r5   r2   rZ  
_tag_names)r6   r2   r7   rG  rH  rI  rJ  rK  rL  rM  rN  rO  rP  rV  train_fn_kwargseval_fn_kwargsr)  s                   r;   r(  _UnslothPRMTrainer.__init__  s6   (  $U+".O ' t  ??O\k\klMm888224!1&*&9&9"&//)-)?)?-1-G-G/3/K/K	 #BY"A	5"A - 1 1%%-!22#0#9#93%..&.&7&7w8O&P)1):):8>>';R)S !2 ! "@I!?y$!?+#/#3#3))"0!%!6!6'3'<'<6!)!2!2*2*;*;HNN7<S*T-5->->x~~g?V-W" $4 $L5 5P 	''%-!+!*G 	 	
 4::/00JJ%%doo6 1o 54s   5FI
I%c                    U" U S   SS9S   nU S    V	s/ s H  o" U	SS9S   PM     n
n	U(       a0  U(       d)  S/[        U S   5      S-
  -  [        U S   S	   5      /-   nOU S    Vs/ s H  n[        U5      PM     nnUR                  USS9nU
 V	s/ s H  oU-   PM	     n
n	[        X5       V	Vs/ s H  u  pS/[        U	5      S-
  -  U/-   PM     nn	n[	        [        U
6 5      n[	        [        U6 5      nUR                  b  UR                  /U-   nUb  X* S
 nUb
  US
U nUS
U nX-   nS/[        U5      -  U-   nUb
  US
U nUS
U nXS.$ s  sn	f s  snf s  sn	f s  snn	f )a  
Tokenize a row of the dataset.

Args:
    features (`dict[str, str]`):
        Row of the dataset, should contain the keys `"prompt"`, `"completions"`, and `"labels"`.
    tokenizer (`PreTrainedTokenizerBase`):
        Tokenizer used to process the data.
    step_separator (`str`):
        Separator between steps in the completion.
    max_length (`int` or `None`):
       Maximum length of the sequences (prompt + completion). If `None`, the sequences are not truncated.
    max_prompt_length (`int` or `None`):
        Maximum length of the prompt. If `None`, the prompt is not truncated.
    max_completion_length (`int` or `None`):
        Maximum length of the completion sequences. If `None`, the completion sequences are not truncated.
    train_on_last_step_only (`bool`):
        Whether to train only on the last step. If `True`, the labels are `-100` for all tokens except the last
        token of the completion.
    is_eval (`bool`):
        Whether the function is used to tokenize samples from a training or an evaluation dataset. Used only if
        `train_on_last_step_only` is set to `True`.

Returns:
    `dict[str, list[int]]`:
        Tokenized sequences with the keys `"input_ids"`, and `"labels".

Example:
```python
>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
>>> features = {
...     "prompt": "Which number is larger, 9.8 or 9.11?",
...     "completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
...     "labels": [True, False],
... }
>>> PRMTrainer.tokenize_row(
...     features, tokenizer, "\n", max_completion_length=None, train_on_last_step_only=False, is_eval=False
... )
{'input_ids': [23085, 1372, 374, 8131, 11, 220, 24, 13, 23, 476, 220, 24, 13, 16, 16, 30, 16, 16, 374, 7046, 1091, 220, 23, 13, 198, 39, 763, 11, 220, 24, 13, 16, 16, 861, 220, 24, 13, 23, 13, 198],
 'labels': [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0]}
```
promptF)add_special_tokensrf   completionsirU  rO   rI   N)rf   rU  )lenr?  encoderS   listr   bos_token_id)r   rR  r  r  r  r  r   rS  
prompt_ids
completioncompletions_idsrU  labelseparator_idscompletion_idsrf   s                   r;   r^  _UnslothPRMTrainer.tokenize_rowh  s   p x1eL[Y
[cdq[r
[rZIjU;KH[r 	 
 #7Vs8H#56:;s8HCUVXCY?Z>[[F.6x.@A.@Uc%j.@FA "((E(RHWX*5X UXXgTpqTp?Pz4&C
Oa/0E7:Tpq e_56eVn%!!-#001J>J (#$6$78J ,+,B-BCN223F/	#j/)F2!!+:.IKZ(F&99I
 B Y rs   E(EE1"E 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/rI   )
model_name)	r7   r   r   r   namesplitcreate_model_cardr'  _save_checkpoint)r6   r2   trialrw  r)  s       r;   r{  #_UnslothPRMTrainer._save_checkpoint  sj    99!!)dii22388J//55c:2>J*5 .r>   rw  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SUS	S
9	nUR/                  [        R
                  R1                  U R2                  R4                  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_jobsa          @article{uesato2022solving,
            title        = {{Solving Math Word Problems With Process- and Outcome-Based Feedback}},
            author       = {Uesato, Jonathan and Kushman, Nate and Kumar, Ramana and Song, Francis and Siegel, Noah and Wang, Lisa and Creswell, Antonia and Irving, Geoffrey and Higgins, Irina},
            year         = 2022,
            journal      = {arXiv preprint arXiv:2211.14275}
        }PRMzBSolving math word problems with process-and outcome-based feedback)	
base_modelrw  r   r~  r  	wandb_urltrainer_nametrainer_citationpaper_titlez	README.md)is_world_process_zeror5   r2   configr#   pathisdirr  set
isinstancestraddenvironupdaterb  r%   dedentr    r   r!   wandbrunurlsavejoinr7   r   )r6   rw  r~  r  r  citation
model_cards          r;   rz  $_UnslothPRMTrainer.create_model_card  se   " ))++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[_%\


 	TYY%9%9;GHr>   r"  )NNNNNNNNN)NNNN)NNN)&r9  r:  r;  r<  r=  rb  r   r	   r   r"   Moduler   r   r   dictr  r   r   r   r   r   r   rl  r   tupler&   r   	Optimizerlr_schedulerLambdaLRr   r(  staticmethodr^  r{  rz  r@  rA  rB  s   @r;   rD  rD    s   #J J >B$(04+/EI >BFJ59W
 im&*%^7oryy89:^7 y!^7  -	^7
  (^7 uWd3<.@%@AB^7 #)+=?UWeef
^7 Xb/&9:;^7 "(N+;T+A"BC^7 D12^7 %++//1I1I1R1RRS^7" (0%,,9UW\WcWc9c0d'e#^7$ d^%^7 ^7@ \: \:~/ %)&*,0	>ISM>I sm>I CcD()	>I >Ir>   rD  c                   F   ^  \ rS rSrSr           SU 4S jjrSrU =r$ )UnslothPRMTraineri  a  
    
Initialize PRMTrainer.

Args:
    model (`transformers.PreTrainedModel`):
        The model to train, preferably an `AutoModelForTokenClassification`.
    args (`PRMConfig`):
        The arguments to use for training.
    data_collator (`transformers.DataCollator`):
        The data collator to use for training. If None is specified, the default data collator
        (`DataCollatorForTokenClassification`) 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`):
        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.
    model_init (`Callable[[], transformers.PreTrainedModel]`):
        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 `compute_accuracy`):
        The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`)
        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.

    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_PRECISIONrU   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_PRECISIONrI  r   r   r   r-  r   rO   )__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   bfloat16rL  rO  UNSLOTH_RETURN_LOGITSr   r3   rR  padding_siderightrJ  )UnslothVisionDataCollatorrU  r4  pad_to_multiple_of)mlmmlm_probabilityr  )r  r   dataset_text_fieldr3  dataset_kwargsskip_prepare_datasetpad)PatchRLStatisticsprm_trainerparallel_mode_n_gpur2   )r2   r7   rG  rH  rI  rJ  rK  rL  rM  rO  rP  r4   neftune_hook_handler  acceleratortrainr"  )?r   getattrtypeboolr#   r  getr#  r  get_input_embeddingsr  unsloth_zoo.utilsr  r&   float16	TypeErrorr   r   r   r   transformersr  r*   r   r   r   r   r   localsr5   r   r3   rR  r  unsloth_zoo.vision_utilsr  r  r,   r[  +TransformersDataCollatorForLanguageModelingr   r  r  unsloth_zoo.logging_utilsr  r.   NOT_DISTRIBUTEDn_gpur  r'  r(  r4   r  remover  r  scaleraccelerator_scalerr2   r/   rA   r)  r  )%r6   r2   r7   rG  rH  rI  rJ  rK  rL  rM  rO  rP  r8   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   _UnslothPRMTrainer__tokenizerr  other_metricsr  r  current_modelr)  s%                                       r;   r(  UnslothPRMTrainer.__init__6  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))'/#-!,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r>   )r  )NNNNNNNNNNN)r9  r:  r;  r<  r=  r(  r@  rA  rB  s   @r;   r  r    s8    %P (,e er>   r  )Fr=  r&   r   torch.nnr"   r   Ftypingr   r   r   r   r	   r
   r   r   trl.trainer.prm_trainerr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r#   r$   r%   dataclassesr(   r)   packaging.versionr*   numpynp
contextlibr+   r  r,   r-   r  transformers.training_argsr.   r?   typesr/   rA   torch_compile_optionscompilere   r?  rp   r~   r   r   rD  r  r"  r>   r;   <module>r     s  0    $ I I I x  x  x  x  x  x  x  x  x 
  ( %   " $  3      4;PR S"||  \\	&,, %  	
 \\6ell C ELL  N-y N- N-^
 nI nI^	L* L\ r>   