
    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/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>J?r?J@r@JArAJBrBJrJCrCJDrDJErEJFrFJGrGJHrHJIrIJJrJJKrKJLrLJMrMJNrNJOrOJPrPJQrQJRrRJSrSJTrTJrJUrUJVrVJWrWJXrXJYrYJrJrJrJ(r(J)r)J*r*J0r0J1r1J6r6J8r8J>r>J?r?JBrBJCrCJDrDJErEJKrKJMrMJrJUrUJVrVJXrXJrJ0r0J9r9JrJCrCJDrDJLrLJMrMJrJrJLrLJMrMJQrQJRrRJSrSJrJWrWJ
r
JrJ%r%J=r=JDrDJMrMJrJrJrJDrDJMrMJrJrJMrMJr  SSKDrDSSK7  SSKZJ[r[J\r\  SS	K]J^r^  SSKrSSK_r`SS
KaJCrC  SSKJr  SSKUJbrbJcrd  SSKeJfrf  SSKgrgSSKhJiri  S rj SSSSSS.rk\R                  " SS\kS9S 5       rmS\R                  S\nS\nS\R                  4S jroS\R                  S\R                  S\nS\nS\R                  4
S jrpS\R                  S\nS\R                  4S jrqS  rr\[ " S! S"\5      5       rs  " S# S$\%5      rt " S% S&\t5      ru \v" \=S'5      (       a3  SSK>r> " S( S)\>R                  5      rx \=R                  " \x" 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)r   
AutoConfig"AutoModelForSequenceClassificationAutoProcessorAutoTokenizer
DataLoaderDatasetFSDPGenerationConfigIterableDatasetr   Path
PeftConfigPreTrainedModelPreTrainedTokenizerBaseProcessorMixin
RLOOConfigRLOOTrainerRepeatSampler
RewardFuncSamplerSyncRefModelCallbackTrainerTrainerCallbackr	   
VLLMClientapply_chat_templatebroadcast_object_listcopydatasetsdefaultdictdequedisable_dropout_in_modelentropy_from_logitsgathergather_objectgenerate_model_cardget_comet_experiment_urlidentityinspectis_conversationalis_datasets_availableis_flash_attn_2_availableis_peft_modelis_rich_availableis_vllm_availableis_wandb_availableloggerloggingmaybe_apply_chat_templatenanmaxnanminnanstdnnnullcontextospadpartialprepare_deepspeedprepare_fsdpprepare_peft_modelprint_prompt_completions_sampleprofiling_contextprofiling_decoratorreseed_workerselective_log_softmaxset_seedshuffle_sequence_dictsplit_pixel_values_by_gridsplit_tensor_dicttextwraptorchtransformerstruncate_with_protected_tokensunsplit_pixel_values_by_gridunwrap_model_for_generationwarningsr   r   r	   r$   r%   r&   r,   r-   r2   r4   r:   r;   r>   r@   rA   rB   rH   rJ   rR   rS   rT   rV   r   r,   r5   r?   r@   rA   rI   rJ   r   r	   rI   rJ   rN   rO   rP   rR   rU   r   r   r!   r9   rA   rJ   rR   r   r?   rA   rJ   r   r?   rJ   rR   )*)	dataclassfield)Version)r@   )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)hasattrrb   rc   rd   )selfargskwargsoutputfs       ?/home/james-whalen/unsloth_compiled_cache/UnslothRLOOTrainer.pywrapper*prepare_for_training_mode.<locals>.wrapper0   sx     4!!gdjj.&I&IJJ##%4)$)&)4!!gdjj/&J&JJJ$$&    )	functoolswraps)rj   rl   s   ` rk   prepare_for_training_moderq   /   s%    __Q  Nrn   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)r|   indexr|      )rR   chunkreshapeshapeziptofloat32r,   	unsqueezesqueeze	logsumexpappendconcat)
logitsr}   chunked_logitschunked_indexall_per_token_logpschunk_logitschunk_indexselected_logitslogsumexp_valuesper_token_logpss
             rk   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rn   	input_idslogits_to_keeppad_token_idreturnc                 ~    XR                   S   :  a  [        S5      eU SS2SU* 24   nX2:H  nUR                  SS9nU$ )zr
Given prompt tensor, it returns all the left padded tokens in that sequence. so [pad, pad, pad, cat] = 3 tokens 
r   z8logits_to_keep must be smaller than the sequence length.Nr~   )r   
ValueErrorsum)r   r   r   prompt_sectionpadding_maskpad_token_countss         rk   calculate_pad_tokens_in_promptr   W   sX     ++STTq"2N?"223N"2L#''A'.rn   completion_input_idsleft_pad_tokens_per_promptmax_left_padc                     U R                   u  pEU R                  nX!-
  n[        R                  " XVS9R	                  S5      nXR	                  S5      :  n	X:g  n
X-  nU$ )a)  
Given that we have a sequence, [p,p,p,c,c,c,pad,pad,pad]

Where p are extra prompt tokens we got from slicing the torch tensor, c is completion tokens
and pad are pad tokens, this function would make a completion mask that would 0 out the pad
and p tokens. so in this example [0,0,0,1,1,1,0,0,0]
devicer   r   )r   r   rR   aranger   )r   r   r   r   
batch_sizecompletion_lenr   num_tokens_to_maskindices
shift_masknon_padding_mask
final_masks               rk    create_completion_attention_maskr   j   si     "6!;!;J!((F%Bll>9CCAFG88;;J,<.Jrn   tensorpad_idc                 l    X:g  n[         R                  " USSSS9n[         R                  " U SU5      nU$ )zD
Moves all padding tokens in each sequence of a batch to the right.
r   T)r|   
descendingstable)rR   argsortr,   )r   r   masksorted_indicespacked_tensors        rk   left_pack_paddingr      s8     D]]4Q4MNLLN;Mrn   c                  .    SSK Jn  U" S0 U D6nXl        U$ )Nr   )SamplingParams )vllmr   _set_kwargs)rh   r   sampling_paramss      rk   vLLMSamplingParamsr      s    #$.v.O"(rn   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SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS S SSSSS!S"SSSSSSSS#SSSSSSSSSSSSSS#SSSSSSS$S%SSSS&SSSSSSSSSSSS'SSSSSSSSS"SSSS#SSSS(S)SSSSSSSSSSSSSSSS*S+S,SSSSSSSS0 SSSSS-S.SSS/S0S1S2SS3SS4SSSSSSS5S*SSSSSSSSSSSSSSSSSSSSS4U 4S6 jjrS7rU =r$ )8UnslothRLOOConfig   u.  
    
Configuration class for the [`RLOOTrainer`].

This class includes only the parameters that are specific to RLOO 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:
    > Parameters that control the model and reference model

    model_init_kwargs (`str`, `dict[str, Any]` or `None`, *optional*, defaults to `None`):
        Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
        argument of the [`GRPOTrainer`] is provided as a string.
    disable_dropout (`bool`, *optional*, defaults to `False`):
        Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
        the model from generating different logprobs for the same input.

    > Parameters that control the data preprocessing

    remove_unused_columns (`bool`, *optional*, defaults to `False`):
        Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
        requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
    max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
        Maximum length of the prompt. If the prompt is longer than this value, it will be truncated left.
    num_generations (`int` or `None`, *optional*, defaults to `2`):
        Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size
        * gradient_accumulation_steps) must be evenly divisible by this value.
    max_completion_length (`int` or `None`, *optional*, defaults to `256`):
        Maximum length of the generated completion.
    ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
        This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
        improving generation speed. However, disabling this option allows training models that exceed the VRAM
        capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
        with vLLM generation.
    shuffle_dataset (`bool`, *optional*, defaults to `True`):
        Whether to shuffle the training dataset.

    > Parameters that control generation

    generation_batch_size: (`int` or `None`, *optional*, defaults to `None`):
        Batch size to use for generation. If `None`, it defaults to the effective training batch size:
        `per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one
        generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`.
    steps_per_generation: (`int` or `None`, *optional*, defaults to `None`):
        Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive
        with `generation_batch_size`.
    temperature (`float`, defaults to `1.0`):
        Temperature for sampling. The higher the temperature, the more random the completions.
    top_p (`float`, *optional*, defaults to `1.0`):
        Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
        `1.0` to consider all tokens.
    top_k (`int` or `None`, *optional*, defaults to `None`):
        Number of highest probability vocabulary tokens to keep for top-k-filtering. If `None`, top-k-filtering is
        disabled and all tokens are considered.
    min_p (`float` or `None`, *optional*, defaults to `None`):
        Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
        value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
    repetition_penalty (`float`, *optional*, defaults to `1.0`):
        Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
        Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
        tokens.
    use_transformers_paged (`bool`, *optional*, defaults to `False`):
        Whether to use the `transformers` paged implementation for generation. If set to `True`, the `transformers`
        paged implementation will be used for generation instead of the default padded implementation. This
        parameter is only effective when `use_vllm` is set to `False`.
    cache_implementation (`str` or `None`, *optional*, defaults to `None`):
        Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
    generation_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
        Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if
        using vLLM) when sampling completions. This can be used to further customize the generation behavior, such
        as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation
        parameters (like `min_p`, `top_p`, etc.), they will override them.

    > Parameters that control generation acceleration powered by vLLM

    use_vllm (`bool`, *optional*, defaults to `False`):
        Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
        instead of the default model.generate(). Requires `vllm` to be installed.
    vllm_mode (`str`, *optional*, defaults to `"server"`):
        Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
        `"colocate"`.

        - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
          server is running (start with `trl vllm-serve`).
        - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
          separate server but may cause resource contention with training.
    vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
        Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
        the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
        implementation.
    vllm_guided_decoding_regex (`str` or `None`, *optional*, defaults to `None`):
        Regex for vLLM guided decoding. If `None` (default), guided decoding is disabled.

    > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)

    vllm_server_base_url (`str` or `None`, *optional*, defaults to `None`):
        Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
        `vllm_server_port` are ignored.
    vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
        Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
    vllm_server_port (`int`, *optional*, defaults to `8000`):
        Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
    vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
        Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
        timeout, a `ConnectionError` is raised.

    > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)

    vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
        Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
        `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
        launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
    vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
        Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
        `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
        launching the vLLM server via the `--vllm_tensor_parallel_size` flag.

    > Parameters that control the training

    beta (`float`, *optional*, defaults to `0.05`):
        KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving training
        speed.
    num_iterations (`int`, *optional*, defaults to `1`):
        Number of iterations per batch (denoted as μ in the algorithm).
    epsilon (`float`, *optional*, defaults to `0.2`):
        Epsilon value for clipping.
    epsilon_high (`float` or `None`, *optional*, defaults to `None`):
        Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
        specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
    reward_weights (`list[float]` or `None`, *optional*, defaults to `None`):
        Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
        weighted equally with weight `1.0`.
    normalize_advantages (`bool`, *optional*, defaults to `False`):
        Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` and standard
        deviation of `1.0`.
    reward_clip_range (`tuple[float, float]` or `None`, *optional*, defaults to `None`):
        Clip range for rewards as (min, max). If `None`, no clipping is applied.
    mask_truncated_completions (`bool`, *optional*, defaults to `False`):
        When enabled, truncated completions are excluded from the loss calculation, preventing them from being
        incorrectly penalized and introducing noise during training. According to the
        [DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability.
    sync_ref_model (`bool`, *optional*, defaults to `False`):
        Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
        the `ref_model_mixup_alpha` parameter. This synchronization originates from the
        [TR-DPO](https://huggingface.co/papers/2404.09656) paper.
    ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
        α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
        between the current policy and the previous reference policy during updates. The reference policy is
        updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
        must set `sync_ref_model=True`.
    ref_model_sync_steps (`int`, *optional*, defaults to `512`):
        τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
        frequently the current policy is synchronized with the reference policy. To use this parameter, you must
        set `sync_ref_model=True`.

    > Parameters that control the logging

    log_completions (`bool`, *optional*, defaults to `False`):
        Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
        it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`.
    num_completions_to_print (`int` or `None`, *optional*, defaults to `None`):
        Number of completions to print with `rich`. If `None`, all completions are logged.
    wandb_log_unique_prompts (`bool`, *optional*, defaults to `False`):
        Whether to log unique prompts in wandb. If `True`, only unique prompts are logged. If `False`, all prompts
        are logged.

    NhelpzvLLM SamplingParams)defaultmetadatavllm_sampling_paramsry   z8Chunk size to reduce memory usage. -1 is most efficient.unsloth_num_chunksFnorz      r      g-C6
?g{Gz?g?g+?g:0yE>      ?g      @linear皙?passivewarningTstepsr     iO  O1auto         
adamw_8bitlength
every_savelasti           colocater   z0.0.0.0i@  g      n@g333333?g?g?g333333?c                   > 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      nUW-  U-  U:w  a(  [        S[        U5      -   S-   [        W5      -   5        UnWS
::  a  [        S5      eWS:  a  [        S5      e[        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_S0U_S1U_S2U_S3U _S4U!_S5U"_S6U#_S7U$_S8U%_S9U&_S:U'_S;U(_S<U)_S=U*_S>U+_S?U,_S@U-_SAU._SBU/_SCU0_SDU1_SEU2_SFU3_SGU4_SHU5_SIU6_SJU7_SKU8_SLU9_SMU:_SNU;_SOU<_SPU=_SQU>_SRU?_SSW@_STWA_SUWB_SVWC_SWWD_SXWE_SYWF_SZWG_S[WH_S\WI_S]WJ_S^WK_S_WL_S`WM_SaWN_SbWO_ScWP_SdWQ_SeWR_SfWS_SgWT_ShWU_SiWV_SjWW_SkWX_SlWY_SmWZ_SnW[_SoW\_SpW]_SqW^_SrW__SsW`_StWa_SuWb_SvWc_SwWd_SxWe_SyWf_SzWg_S{Wh_S|Wi_S}Wj_S~Wk_SWl_SWm_SWn_SWo_SWp_SWq_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_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_SW_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
        g )NgHz>z Unsloth: Your learning rate of `zi` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!r   za` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!r   r   unsloth_training_checkpointsr   r   )	cpu_countrz   r   @   z}Unsloth: We now expect `per_device_train_batch_size` to be a multiple of `num_generations`.
We will change the batch size of z to the `num_generations` of zUUnsloth: Please set a positive non-zero temperature since your results will be wrong.
   zgUnsloth: Please set a positive non-zero temperature less than 10, since sampling will be quite erratic.
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model_init_kwargsdisable_dropoutmax_prompt_lengthnum_generationsmax_completion_lengthds3_gather_for_generationshuffle_datasetgeneration_batch_sizesteps_per_generationtemperaturetop_ptop_kmin_pgeneration_kwargsrepetition_penaltyuse_transformers_pagedcache_implementationuse_vllm	vllm_modevllm_model_implvllm_guided_decoding_regexvllm_server_base_urlvllm_server_hostvllm_server_portvllm_server_timeoutvllm_gpu_memory_utilizationvllm_tensor_parallel_sizebetanum_iterationsepsilonepsilon_highreward_weightsnormalize_advantagesreward_clip_rangemask_truncated_completionssync_ref_modelref_model_mixup_alpharef_model_sync_stepslog_completionsnum_completions_to_printwandb_log_unique_promptsrloo_k	cliprangekl_coefexp_namenormalize_rewardnum_ppo_epochsnum_mini_batchestotal_episodesresponse_lengthtoken_level_kldataset_num_proc local_rollout_forward_batch_sizenum_sample_generations
stop_tokenstop_token_idmissing_eos_penaltyr   )printmultiprocessingr   minmaxstr	MathErrorsuper__init__r   r   )rf   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  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  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  re  rf  rg  rh  ri  rj  rk  rl  rm  rn  ro  rp  rq  rr  rs  rt  ru  rv  rw  rx  ry  rz  r{  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   rh   r   	__class__s                                                                                                                                                                                                  rk   r  UnslothRLOOConfig.__init__J  sS   B 4)I-  YB  (C  "D1e&F}o  Vw  %x  y-7":zS?P7J M#1"3y{1}a#8"='?:oMQll  S  VY  Zu  Vv  v  yX  X  [^  _n  [o  o  p*9'!sttB  F  G  G 	 z	@#z	@#7z	@  z	@ 	z	@
 $z	@ *z	@ $8z	@ +Fz	@ *Dz	@ (@z	@ '>z	@ +Fz	@ '>z	@ $z	@ '>z	@  *!z	@" (#z	@$ $%z	@& $'z	@( ()z	@* *+z	@,  0-z	@. "/z	@0 !21z	@2 (3z	@4 (5z	@6 "7z	@8 !29z	@:  0;z	@< &=z	@>  0?z	@@ "4Az	@B *Cz	@D &<Ez	@F *Gz	@H $Iz	@J  0Kz	@L  0Mz	@N !2Oz	@P .Qz	@R 7^Sz	@T Uz	@V Wz	@X ,Yz	@Z [z	@\ "]z	@^ *_z	@`  az	@b cz	@d ez	@f ,gz	@h &<iz	@j ,kz	@l ,mz	@n oz	@p $qz	@r &sz	@t *uz	@v !2wz	@x yz	@z $8{z	@| $}z	@~ &<z	@@ *DAz	@B $Cz	@D  Ez	@F (Gz	@H %:Iz	@J &Kz	@L &<Mz	@N %:Oz	@P !2Qz	@R  0Sz	@T Uz	@V #6Wz	@X &Yz	@Z 2T[z	@\ "4]z	@^ "4_z	@` "az	@b &<cz	@d ez	@f $gz	@h "iz	@j .kz	@l "4mz	@n "oz	@p *Dqz	@r !2sz	@t %:uz	@v %:wz	@x -Jyz	@z #6{z	@| *D}z	@~ &z	@@ &<Az	@B (Cz	@D (Ez	@F "Gz	@H  0Iz	@J .Kz	@L (Mz	@N &<Oz	@P -JQz	@R *DSz	@T &<Uz	@V (Wz	@X $8Yz	@Z (@[z	@\ !2]z	@^ *_z	@` $8az	@b  0cz	@d &ez	@f "gz	@h &iz	@j *kz	@l %:mz	@n "4oz	@p )Bqz	@r -Jsz	@t #6uz	@v $8wz	@x "4yz	@z *{z	@|  0}z	@~ #6z	@@ &<Az	@B -JCz	@D !2Ez	@F .Gz	@H !2Iz	@J .Kz	@L %:Mz	@N )BOz	@P .Qz	@R %:Sz	@T $8Uz	@V &Wz	@X Yz	@Z [z	@\ ]z	@^ !2_z	@` "4az	@b &<cz	@d $8ez	@f  gz	@h "iz	@j .kz	@l *Dmz	@n $8oz	@p  0qz	@r  0sz	@t #6uz	@v +Fwz	@x )Byz	@z {z	@| ,}z	@~ z	@@ (Az	@B ,Cz	@D $8Ez	@F !2Gz	@H *DIz	@J ,Kz	@L %:Mz	@N $8Oz	@P .Qz	@R (@Sz	@T (@Uz	@V Wz	@X "Yz	@Z [z	@\  ]z	@^  0_z	@` ,az	@b  0cz	@d ,ez	@f .gz	@h ,iz	@j  0kz	@l 0Pmz	@n &<oz	@p $qz	@r *sz	@t #6uz	@v %9!"4rn   )r   r   )__name__
__module____qualname____firstlineno____doc__rZ   r   r   r   __annotations__r   intr  __static_attributes____classcell__r  s   @rk   r   r      s   kX +012+(3-  */VW*#  #$&'%&#'"&&'"#"%$%""!&!27!'!$!"%) %!& $  -1!!!$%%)  $ $(-"%*!%#!%(,%*!%##' $  $!$)(-"#" "!&(,  #$( $# !&# %)#$#&)$%$ %* #"#'#(+/!%"#{O5 O5rn   r   c                      ^  \ rS rSrSrSS/r               S2S\\\4   S\\	\
\	   4   S\\   S	\\\\4      S
\\\\\\\\\4   4   4      S\\\\4      S\\\\
\   4      S\\
\      S\\\R*                  R,                     \\R*                  R.                  R0                     4   S\S   4U 4S jjjrS rS rS3S\\   S\4S jjrS\4S jr\  S4S\\\\R@                     4   4S jj5       r!S3S\\
\      4S jjr"S5S\#RH                  S\4S jjr%S\#RH                  4S jr&\S 5       r'\S \\\\R@                  \(4   4   S\\\\R@                  \(4   4   4S! j5       r)\U 4S" j5       r*S#\
\\\\R@                  \(4   4      S\\\\R@                  \(4   4   4U 4S$ jjr+\S6S% j5       r,S& r-S3S'\\
\      4S( jjr.S3S)\\\/4   S*\\/   SS4U 4S+ jjjr0U 4S, jr1   S7S-\\   S.\\   S/\\\
\   S4   4S0 jjr2S1r3U =r4$ )8_UnslothRLOOTraineri  a  
Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to
Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs]
(https://huggingface.co/papers/2402.14740).

Example:

```python
from datasets import load_dataset
from trl import RLOOTrainer

dataset = load_dataset("trl-lib/tldr", split="train")
def reward_func(completions, **kwargs):
    # Dummy reward function that rewards completions with more unique letters.
    return [float(len(set(completion))) for completion in completions]
trainer = RLOOTrainer(
    model="Qwen/Qwen2-0.5B-Instruct",
    reward_funcs=reward_func,
    train_dataset=dataset,
)

trainer.train()
```

Args:
    model (`Union[str, PreTrainedModel]`):
        Model to be trained. Can be either:

        - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
          path to a *directory* containing model weights saved using
          [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
          using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
          `args.model_init_kwargs`.
        - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
    reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
        Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
        functions with the prompts and completions and sum the rewards. Can be either:

        - A single reward function, such as:
            - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
            path to a *directory* containing model weights saved using
            [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
            using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
            keyword arguments in `args.model_init_kwargs`.
            - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
            - A custom reward function: The function is provided with the prompts and the generated completions,
              plus any additional columns in the dataset. It should return a list of rewards. Custom reward
              functions can also return `None` when the reward is not applicable to those samples. This is useful
              for multi-task training where different reward functions apply to different types of samples. When a
              reward function returns `None` for a sample, that reward function is excluded from the reward
              calculation for that sample. For more details, see [Using a custom reward
              function](#using-a-custom-reward-function).

              The trainer's state is also passed to the reward function. The trainer's state is an instance of
              [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
              reward function's signature.
        - A list of reward functions, where each item can independently be any of the above types. Mixing different
        types within the list (e.g., a string model ID and a custom reward function) is allowed.
    args ([`RLOOConfig`], *optional*, defaults to `None`):
        Configuration for this trainer. If `None`, a default configuration is used.
    train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
        Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
        ignored. The format of the samples can be either:

        - [Standard](dataset_formats#standard): Each sample contains plain text.
        - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
          and content).
    eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
        Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`] or `None`, *optional*, defaults to `None`):
        Processing class used to process the data. The padding side must be set to "left". If `None`, the
        processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
        padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
        `tokenizer.eos_token` will be used as the default.
    reward_processing_classes (`Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]`, *optional*, defaults to `None`):
        Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:

        - A single processing class: Used when `reward_funcs` contains only one reward function.
        - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
        If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
        `None`, the tokenizer for the model is automatically loaded using
        [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
        functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
        are ignored.
    callbacks (list of [`~transformers.TrainerCallback`], *optional*, defaults to `None`):
        List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
        in [here](https://huggingface.co/docs/transformers/main_classes/callback).

        If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
        method.
    optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
        A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
        model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
    peft_config ([`~peft.PeftConfig`], *optional*, defaults to `None`):
        PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
trlrlooNrb   reward_funcsrg   train_dataseteval_datasetprocessing_classreward_processing_classes	callbacks
optimizerspeft_configr   c                 !  >^ [        US5      (       a)  [        TS5      (       a  [        TSS5      S:X  a  STl        Ub'  [        R                  " S5        Tc  UmO[        S5      eUb'  [        R                  " S5        Uc  UnO[        S5      eUb'  [        R                  " S	5        Uc  UnO[        S
5      eUb  [        R                  " S5        Ub  [        R                  " S5        SUR                  ;   a+  [        R                  " S5        S nUR                  USU0S9nUb;  SUR                  ;   a+  [        R                  " S5        S nUR                  USU0S9nTcO  [        U[        5      (       a  UOUR                  R                  nUR                  S5      S   n[        U S35      mTR                  =(       d    0 n[        U[        5      (       a  UnUR                  S5      n[        U[         R"                  5      (       d	  US:X  d  Uc  O:[        U[        5      (       a  [        [         U5      nUUS'   O[        SU S35      e[$        R&                  " U5      n[        [(        UR*                  S   5      nUR&                  " U40 UD6nO9UR                  R                  nTR                  b  [,        R.                  " S5        [        US5      (       d8  [0        R2                  " UR4                  5      R6                  R9                  5       OE[0        R2                  " UR;                  5       R4                  5      R6                  R9                  5       U l         Uc*  [@        R&                  " UR                  R                  5      n[        U[B        5      (       a  URD                  nO#[        U[F        5      (       a  UnO[I        S5      eURJ                  c  URL                  Ul%        URJ                  U l%        URN                  U l'        URP                  U l(        [        U[R        5      (       d  U/n/ U l*        [W        U5       H  u  nn[        U[        5      (       a  [X        R&                  " U4SS 0UD6UU'   [        UU   [Z        R\                  5      (       aF  U RT                  R_                  UU   R                  R                  R                  S5      S   5        M  U RT                  R_                  UU   R`                  5        M     X l1        TRd                  b  [g        TRd                  5      [g        U5      :w  a.  [        S![g        TRd                  5       S"[g        U5       S#35      e[         Rh                  " TRd                  [         Rj                  S$9U l2        O1[         Rl                  " [g        U5      [         Rj                  S$9U l2        Uc  S /[g        U5      -  nO[        U[R        5      (       d  U/n[g        U5      [g        U5      :w  a$  [        S%[g        U5       S&[g        U5       S'35      e[W        [o        Xr5      5       H  u  nu  nn[        U[p        5      (       d  M   Uc*  [r        R&                  " UR                  R                  5      nURN                  c  URL                  Ul%        URN                  UR                  l'        UUU'   M     Xpl:        TRv                  U l;        TRx                  U l<        TRz                  U l=        TR|                  U l>        TR~                  U l?        TR                  U l@        TR                  U lA        TR                  U lB        TR                  U lC        TR                  U l        TR                  U lD        TR                  U lE        TR                  U lF        TR                  U lG        TR                  U lH        TR                  U lI        TR                  U lJ        [        U[        5      (       dO  [        U[        5      (       d:  [        U[        5      (       a0  [        S( UR                  5        5       5      (       a  [        S)5      eTR                  U lP        TR                  U lR        TR                  b  TR                  OTR                  U lS        SU lT        S U lU        SUR                  S*'   [        TU G]a  UT[        UUUUU	S+9  TR                  U lZ        U R                  S,:X  a  S U l[        Oc[        U5      (       a  S U l[        OK[$        R&                  " U5      n[        [(        UR*                  S   5      nUR&                  " U40 UD6U l[        TR                  (       a-  [        U5        U R                  b  [        U R                  5        [        [R        5      [        [R        5      S-.U l`        SU la        TR                  U lb        TR                  U lc        TR                  U ld        [        TR                  S.9[        TR                  S.9[        U4S/ j5      [        TR                  S.9S0.U lg        [        TR                  SS19  U R                  (       Ga^  [        5       (       d  [        S25      eU R                  S3:X  a  U R                  R                  (       a  TR                  b  TR                  nOS4TR                   S5TR                   3n[        UTR                  S69U ls        U R                  R                  [         R                  R                  5       S79  GO^U R                  S8:X  Ga4  U R                  R                  U R                  -  S:X  d0  [        S9U R                   S:U R                  R                   S;35      eU R                  S :  a  [         R                  R                  [        U R                  R                  U R                  -  5       Vs/ s H5  n[S        [        UU R                  -  US -   U R                  -  5      5      PM7     sn5      u  U l{        n[        U R                  R                  5      [        R                  S<'   [        U R                  R                  5      [        R                  S='   [        U R                  R                  5      [        R                  S>'   [        R                  R                  S?S@5      [        R                  S?'   [        R                  R                  SASB5      [        R                  SA'   U Rv                  b'  U Rx                  b  U Rv                  U Rx                  -   nOS nUGR                   U l        O[        SCU R                   SD35      eTGR                  U l        SU l        U R                  GR                  5         OU Rx                  SURN                  UGR                  URP                  U R|                  U R~                  U R                  U R                  U R                  TGR                  SE.nTR                  (       a  SFUSG'   SHUSI'   SJUSK'   TGR                  b  UGR                  TGR                  5        G[        SO0 UD6U l        SU l        U GR                  GR                  U GR                  5        U R                  b  U GR                   (       a'  G[#        U R                  U R                  5      U l[        OcU GR$                  (       a'  G['        U R                  U R                  5      U l[        O*U R                  GR)                  U R                  SSL9U l[        TGR*                  (       a/  U GR-                  G[/        U R                  U R                  SM95        [W        U Rb                  5       H~  u  nn[        U[p        5      (       d  M  U GR                   (       a&  G[#        UU R                  5      U Rb                  U'   MU  U R                  GR)                  USSSN9U Rb                  U'   M     g s  snf )PNvllm_engineru  FTz}Parameter 'config' is deprecated and will be removed in version 0.25.0. Please use 'args' instead. We are setting args=configzMCannot specify both 'config' (deprecated) and 'args'. Please use 'args' only.zParameter 'reward_model' is deprecated and will be removed in version 0.25.0. Please use 'reward_funcs' instead. We are setting reward_funcs=reward_modelzcCannot specify both 'reward_model' (deprecated) and 'reward_funcs'. Please use 'reward_funcs' only.zParameter 'policy' is deprecated and will be removed in version 0.25.0. Please use 'model' instead. We are setting model=policyzOCannot specify both 'policy' (deprecated) and 'model'. Please use 'model' only.zParameter 'ref_policy' is deprecated and will be removed in version 0.25.0. To use the initial model as the reference model, simply omit this parameter. The parameter is ignored.zParameter 'data_collator' is deprecated and will be removed in version 0.25.0. The RLOOTrainer does not use a data collator, so this parameter is ignored.r   a  The training dataset contains a column named 'input_ids', indicating that it is pre-tokenized. Support for pre-tokenized datasets is deprecated and will be removed in version 0.25. Please provide the raw dataset (conversational or standard) with a 'prompt' column instead.c                 .    SUR                  U S   5      0$ Npromptr   decodeexample	tokenizers     rk   r  ,_UnslothRLOOTrainer.__init__.<locals>.decode       )"2"27;3G"HIIrn   r  )	fn_kwargsa  The evaluation dataset contains a column named 'input_ids', indicating that it is pre-tokenized. Support for pre-tokenized datasets is deprecated and will be removed in version 0.25. Please provide the raw dataset (conversational or standard) with a 'prompt' column instead.c                 .    SUR                  U S   5      0$ r  r  r  s     rk   r  r    r  rn   /ry   z-RLOOdtyper   zInvalid `dtype` passed to `RLOOConfig`. Expected either 'auto' or a string representing a `torch.dtype` (e.g., 'float32'), but got .r   zYou passed `model_init_kwargs` to the `RLOOConfig`, but your model is already instantiated. The `model_init_kwargs` will be ignored.get_base_modelzWThe `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`
num_labelsr   zNumber of reward weights (z)) must match number of reward functions ())r  z)The number of reward processing classes (z-) must match the number of reward functions (z).c              3   B   #    U  H  n[        U[        5      v   M     g 7fN)
isinstancer   ).0dss     rk   	<genexpr>/_UnslothRLOOTrainer.__init__.<locals>.<genexpr>%  s     6wav[]z"o7V7Vavs   z^Iterable datasets are not yet supported in RLOOTrainer. Please use a standard dataset instead.estimate_tokens)rb   rg   data_collatorr  r  r  r  r  r   )trainevalmaxlenc                  *   > [        T R                  S9$ )Nr  )r)   rk  )rg   s   rk   <lambda>._UnslothRLOOTrainer.__init__.<locals>.<lambda>i  s    58R8R+Srn   )r  
completionrewards
advantages)device_specificzkvLLM is not available and `use_vllm` is set to True. Please install vLLM with `pip install vllm` to use it.serverzhttp://:)base_urlconnection_timeoutr   r   zvllm_tensor_parallel_size (z) must divide world size (z	) evenly.RANK
LOCAL_RANK
WORLD_SIZEMASTER_ADDR	localhostMASTER_PORT12345z6vllm_mode must be either 'server' or 'colocate', got 'z'.)max_new_tokens	do_sampler   bos_token_ideos_token_idrm  rn  ro  rp  rr  rt  r   max_batch_tokensi   
num_blocks   
block_size)evaluation_mode)	ref_modelaccelerator)r  device_placementr   )re   getattrru  rW   warnr   column_namesmapr  r  config_name_or_pathsplitr   rd  getrR   r  r   from_pretrainedrS   architecturesr9   r   r1   	signatureforward
parameterskeysr  model_kwarg_keysrF   r   r   r  r   	TypeError	pad_token	eos_tokenr   r  listreward_func_names	enumerater   r?   Moduler   r  r  r  lenr   r   onesr   r   r   r  rf  rh  rg  rm  rn  ro  rp  rr  rs  rv  r}  r~  r  r  r  rj  r   dictanyvaluesNotImplementedErrorr  r  epsilon_lowr  _step_buffered_inputswarnings_issuedr  r  r0   r  r  r5   re  r*   r(   _metrics_total_train_tokensr  r  r  r)   rk  _logsrM   r  r7   ImportErrorr  is_main_processry  rz  r{  r#   r|  vllm_clientinit_communicatorcudacurrent_devicenum_processesdistributednew_subgroups_by_enumerationrangetp_groupprocess_indexrA   environlocal_process_indexr  llmrx  guided_decoding_regex_last_loaded_stepwait_for_everyoner  rt  rq  updater   generation_configmodel_accepts_loss_kwargsrb   add_model_tags
_tag_namesis_deepspeed_enabledrD   is_fsdp_enabledrE   prepare_modelr  add_callbackr    )rf   rb   r  rg   r  r  r  r  r  r  r  r   reward_modelpolicy
ref_policyr  r  
model_namerd  model_idr  architecturer  ireward_funcreward_processing_classr  _max_model_lenrq  r  s      `                          rk   r  _UnslothRLOOTrainer.__init__A  s.   * 5-((WT:-F-Fj%0E9 $MM- | !pqq#MMS #+   MM. } !rss!MM` $MMI -444MM_J *--fN^@_-`M#|7P7P(PMM_J (++F{L\>]+^L <",UC"8"8ell>X>XJ#))#.r2JE23D !228beS!!H%))'2E%--&EME3''u--2!'* BBGK 
  //9F"<1E1Ea1HIL 00O=NOE||11H%%1? 5"233 emm,77<<>""5#7#7#9#A#ABMMRRT 	  #,<<U\\=W=WX &77(22I(*ABB(Iuvv&"+"5"5I",,%22%22 ,--(>L!#'5NA{+s++"D"T"T#,-#1B#Q ,q/29955&&--l1o.D.D.R.R.X.XY\.]^`.ab&&--l1o.F.FG 6 ) *4&&'3|+<< 0T5H5H1I0J K""%l"3!4A7  #(,,t/B/B%--"XD"'**S->emm"TD %,)-\1B(B%5t<<)B(C%()S->>;C@Y<Z;[ \%%(%6$7r; 
 :C3G`Co9p5A5'+77*2.;.K.KKL^L^LlLl.m+*77?8O8Y8Y+5 3J2V2V""//F)!, :q *C& "&!7!7%)%?%?"#33++ZZ
ZZ
ZZ
"&"9"9&*&A&A#+/+K+K()-)G)G&$($=$=!*.*I*I'!%!7!7  $33 }o66,88<..36wamatatav6w3w3w &p 
 #11<<151B1B1ND--TXT`T`
 !% 48/0"'%-! 	 		
 II	99!DN5!! "DN  //9F"<1E1Ea1HIL)99(XFWXDN $U+~~)(8 #.d"3[=NO#$ #33(,(E(E%(,(E(E% 4#=#=>t'A'AB"#STt'A'AB	

 	D1===$&&!4 
 ~~)##3300<#'#<#<%,T-B-B,C1TEZEZD[#\'18X\XpXp'qD$$$66ejj>W>W>Y6Z:-''558V8VVZ[[$5d6T6T5U V ,,::;9F 
 11A5','8'8'U'U &+4+;+;+I+ITMkMk+k%l%l !q4+I+I'IAPQEUYUsUsKs!tu%l($DM1 &))9)9)G)G%H

6"+.t/?/?/S/S+T

<(+.t/?/?/M/M+N

<(,.JJNN=+,V

=),.JJNN=',R

=)))5$:T:T:`$($:$:T=W=W$WM$(M ,, #YZ^ZhZhYiik!lmm)-)H)HD&%'D"..0 #'"<"<! ) 6 6 ) 6 6 ) 6 6#//&*&=&=(,(A(A! **8;!"4526!,/25!,/%%1!(()?)?@%5%J8I%JD"
 */& 	

!!$//2>>%(((!24>>4CSCS!T%%%!-dnnd>N>N!O!%!1!1!?!?`d!?!e2T^^Y]YiYijk'(9(9:NA{+77,,,+<[$JZJZ+[D%%a( ,0+;+;+I+I#TD ,J ,D%%a( ;s   2<ABc                 0    U R                   c	  S/U l         g g )Nr  )_signature_columns)rf   s    rk    _set_signature_columns_if_needed4_UnslothRLOOTrainer._set_signature_columns_if_needed  s    
 ""*'/jD# +rn   c                 x   U R                   c  [        S5      eU R                   nU R                  n[        5       (       a0  [	        U[
        R                  5      (       a  U R                  USS9nOU R                  USS9nU R                  U R                  R                  -  UU R                  R                  U R                  R                  U R                  R                  S.n[	        U[        R                   R"                  R$                  5      (       d  U R'                  5       US'   U R                  R(                  US'   [+        [,        U R                  R                  U R                  R.                  S9US'   U R                  R0                  US	'   U R2                  R5                  [7        U40 UD65      $ )
Nz+Trainer: training requires a train_dataset.training)description)r   
collate_fnnum_workers
pin_memorypersistent_workerssampler	drop_last)rN  rankworker_init_fnprefetch_factor)r  r   r  r3   r  r'   r   _remove_unused_columns"_get_collator_with_removed_columns_train_batch_sizerg   rl  r!  r=  r>  rR   utilsdatar   _get_train_samplerr  rC   rK   r*  r"  r  preparer   )rf   r  r  dataloader_paramss       rk   get_train_dataloader(_UnslothRLOOTrainer.get_train_dataloader  st   %JKK**** ""z-AQAQ'R'R 77S]7^M CCM_iCjM 004993Q3QQ'99;;))99"&))"I"I
 -)9)9)I)IJJ+/+B+B+Di(-1YY-K-Kk*29)I)IPTPYPYPgPg3./ 48993W3W/0''
=(VDU(VWWrn   datasetr   c           	         Uc  U R                   n[        UU R                  U R                  R                  U R                  -  U R
                  U R                  R                  -  U R                  U R                  R                  S9$ )N)data_sourcemini_repeat_countr   repeat_countshuffler  )	r  r   rg  rg   rk  r  rl  rj  r  )rf   r`  s     rk   r[  &_UnslothRLOOTrainer._get_train_sampler  sq    2 ?((G"22yy66$:N:NN,,tyy/M/MM((
 	
rn   c                 T    [        UU R                  U R                  R                  S9$ )N)rb  rc  r  )r   rg  rg   r  )rf   r  s     rk   _get_eval_sampler%_UnslothRLOOTrainer._get_eval_sampler(  s&    $"22
 	
rn   c                    U=(       d    UR                  S5      n/ n/ n[        SUR                  S5      U5       H  n	X)X-    n
X9X-    nXS.nSU R                  ;   a  US-   US'   SUS'   U" S
0 UD6R                  nUSS2SS2SS24   nUSS2U* S2SS24   nXR                  -  nU
SS2U* S24   n[        X5      nUR                  U5        U(       d  M  [        R                  " 5          [        U5      nSSS5        UR                  W5        M     [        R                  " USS	9nU(       a  [        R                  " USS	9OSnUU4$ ! , (       d  f       NZ= f)z<Compute log-probs and (optionally) entropies for each token.r   )r   attention_maskr   r   F	use_cacheNry   r~   r   )sizer(  r
  r   rm  rL   r   rR   no_gradr+   cat)rf   rb   r   rk  r   r   compute_entropy	all_logpsall_entropiesstartinput_ids_batchattention_mask_batchmodel_inputsr   completion_idslogps	entropiess                    rk   "_get_per_token_logps_and_entropies6_UnslothRLOOTrainer._get_per_token_logps_and_entropies0  sj     49>>!#4
	1innQ/<E'0BCO#1%:L#M  *9aL  4#8#881?!1C-.(-L%*\*11FAssAI&FA/23F ...F,Q0@-@AN)&AEU#]]_ 3F ;I %$$Y/= =@ 		)+7FEIIm3D	i %_s   .E
E	extra_prefixesc                 ^    U=(       d    / nS/U-   nU H  nUR                  US5      nM     U$ )Nz_checkpoint_wrapped_module.r   )replace)rf   namer|  prefixesprefixs        rk   _fix_param_name_to_vllm+_UnslothRLOOTrainer._fix_param_name_to_vllmb  s8    '-212^CF<<+D rn   moduler  c                    Uc
  [        5       nUR                  5        H%  u  pEU(       a  U SU 3OUnU R                  XVUS9  M'     [        U[        5      (       a  [        R
                  " USSS9   UR                  5        H  u  pxU(       a  U SU 3OUn	U R                  U	S/S9n	X;   a  M-  UR                  U	5        U R                  S:X  aB  U R                  R                  (       a'  U R                  R                  XR                  5        M  U R                  S	:X  d  M   M     SSS5        gg! , (       d  f       g= f)
zdMemory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM.Nr  )r  visitedF)recurse	writebackz_fsdp_wrapped_module.r|  r  r   )setnamed_children_sync_fsdp1_params_to_vllmr  r   summon_full_paramsnamed_parametersr  addrv  r  r   r!  update_named_paramrZ  )
rf   r  r  r  
child_namechild_modulechild_prefix
param_nameparam	full_names
             rk   r  ._UnslothRLOOTrainer._sync_fsdp1_params_to_vllmi  s&    ?eG(.(=(=(?$J7=fXQzl3:L++7 ,  )@ fd##((%P)/)@)@)B%J<B6(!J< 8
I $ < <YXoWp < qI + KK	*~~1d6F6F6V6V((;;IzzR:5 *C QP $PPs   2B/D4%D44
Ec                 x   UR                  5        H  u  p#UR                  (       a%  UR                  [        R                  " S5      5      nUR                  5       nU R                  S:X  a8  U R                  R                  (       a  U R                  R                  X#5        M  U R                  S:X  d  M   M     g )Nr#  r  r   )itemsis_cpur   rR   r   full_tensorrv  r  r   r!  r  )rf   r  r  r  s       rk   _sync_fsdp2_params_to_vllm._UnslothRLOOTrainer._sync_fsdp2_params_to_vllm  s    !<<>KD||f!56%%'E~~)d.>.>.N.N  33D@:- *rn   c                 8   U R                   R                  R                  nUS L=(       a    UR                  S:H  nU(       a  SS KnUR
                  R                  nO[        n[        U R                  5      (       Ga  U" [        U R                  R                  5       5      5         U R                  R                  5         U R                  (       a|  [        U R                   R                  SS 5      nU(       a  [        USS5      OSnUS:X  a  U R                  U R                  5        GO US:X  a  U R!                  U R                  5        OU R                  R#                  5        H  u  pxUR%                  S5      R'                  SS	5      nU R                  R(                  U;   a  MB  S
U;   a  MJ  U R+                  US/S9nU R,                  S:X  aB  U R                   R.                  (       a'  U R0                  R3                  XxR4                  5        M  U R,                  S:X  d  M   M     U R                  R7                  5         S S S 5        GO5U R                  (       a{  [        U R                   R                  SS 5      nU(       a  [        USS5      OSnUS:X  a  U R                  U R                  5        OUS:X  a  U R!                  U R                  5        OU R                  R#                  5        H  u  pxU R+                  U5      nU" U/5         U R,                  S:X  aA  U R                   R.                  (       a&  U R0                  R3                  XxR4                  5        OU R,                  S:X  a    S S S 5        M     U R,                  S:X  a6  U R                   R.                  (       a  U R0                  R9                  5         g U R,                  S:X  a  U R:                  R9                  5         g g ! , (       d  f       N= f! , (       d  f       GM"  = f)N   r   fsdp_pluginfsdp_versionr   r   zbase_model.model.z.base_layerr   original_modulezmodules_to_save.default.r  r  r   )r  statedeepspeed_plugin
zero_stager2  zeroGatheredParametersr@   r5   rb   r  r  merge_adapterr7  r  r  r  r  removeprefixr~  r  r  rv  r   r!  r  rZ  unmerge_adapterreset_prefix_cacher-  )	rf   r  zero_stage_3r2  gather_if_zero3r  r  r  r  s	            rk   _move_model_to_vllm'_UnslothRLOOTrainer._move_model_to_vllm  s(     ++11BB't3X8H8S8SWX8X'nn??O)O$$ !djj&;&;&=!>?

((* '' #*$*:*:*@*@-QU"VKNY7;#J_`L#q(77 JJ &*77

C (,zz'B'B'D#001DEMMm]_`::,,4$,4$#;;DRlQm;n>>X5$:J:J:Z:Z ,,??jjQ!^^z9  ! (E$ 

**,G @?N ##%d&6&6&<&<mTRJUw{NAF[\1$33DJJ?!Q&33DJJ?#'::#>#>#@KD77=D(%1>>X5$:J:J:Z:Z ,,??jjQ!^^z9   21 $A >>X%$*:*:*J*J//1^^z)HH'') *{ @?b 21s    'E=O8(O8A$P	8
P	
P	generation_batchc                 l   U R                   R                  (       a  SOSnUS:X  a  U R                  R                  U R                  -  nU R
                  U-  S:X  d  U R                  cg  U R                  U5      n[        U5      n[        U5      n[        XR                  R                  5      nU Vs/ s H  n[        U5      PM     snU l        U R                  U R
                  U R                  R                  -     nU =R
                  S-  sl        U$ U R                  U5      nU$ !    N= fs  snf )Nr  r  r   r   )rb   rK  rg   rl  r  r  r  _generate_and_score_completionsrO   rN   rP   rU   )rf   r  modegenerate_everygeneration_batchesbatchinputss          rk   _prepare_inputs#_UnslothRLOOTrainer._prepare_inputs  s   " **--w67?!YY;;d>Q>QQNzzN*a/43H3H3P#'#G#GHX#Y #=>N#O (=>N(O% &77GIgIg%h"Zl(mZlQV)Ee)LZl(m%**4::		8V8V+VWFJJ!OJ
  99:JKF (ms   D* 3D1*D.c           
        > U R                   R                  n[        R                  " [	        U5      [	        U R
                  5      US9nUS    Vs/ s H  owS;  d  M
  UPM     nnU VV	s0 s H  owU V	s/ s H  oU   PM	     sn	_M     n
nn	U R                  U
S'   [        [        U R
                  U R                  U R                  5      5       GHk  u  nu  pn[        X5         [        U[        R                  5      (       a  [        US   5      (       aE  [        X#5       VVs/ s H  u  nnSUU-   0PM     nnnU Vs/ s H  n[!        UU5      S   PM     nnO#[        X#5       VVs/ s H  u  nnUU-   PM     nnnU" USSS	S
S9n["        TU ]I  U5      n[        R&                  " 5          U" S0 UD6R(                  S S 2S4   US S 2U4'   S S S 5        O[U" SX#US.U
D6nU Vs/ s H  nUb  UO[        R*                  PM     nn[        R,                  " U[        R.                  US9US S 2U4'   S S S 5        GMn     [        R0                  " U5      R3                  SS9R5                  5       (       a  [        R0                  " U5      R3                  SS9R7                  SS9S   S   nU
R9                  5        VVs0 s H  u  nnUS:w  d  M  UUU   _M     nnnUU   US'   UU   US'   [:        R<                  " SU S35        [?        U5      nU$ s  snf s  sn	f s  sn	nf s  snnf s  snf s  snnf ! , (       d  f       GN= fs  snf ! , (       d  f       GM  = fs  snnf )Nr   r   )r  r  rw  trainer_statemessagestextptTrightFr  return_tensorspaddingpadding_sideadd_special_tokens)promptscompletionsrw  r  r   r   r~   )as_tupler  r  z=All reward functions returned None for the following kwargs:
zH
Please ensure that at least one reward function returns a valid reward.r   ) r  r   rR   zerosr  r  r  r  r   r  r  rH   r  r?   r  r2   r$   r  r  inference_moder   nanr   r   isnanallr  nonzeror  r9   r   r,   )rf   r  r  r  completion_ids_listr   rewards_per_funckeyr	  r  reward_kwargsr@  rA  rB  reward_func_namepcr  xtextsreward_inputsoutput_reward_funcrewardnan_row_idxvaluerow_reward_kwargsr  s                             rk   _calculate_rewards&_UnslothRLOOTrainer._calculate_rewards  so   !!(( ;;s7|S9J9J5KTZ[  &ayby7a,aybNRSds6B6s|6BBdS *.o&KT!!4#A#A4CYCYZL
GAG6F #4:k29955(33DGD]#^D]DAqZQ$7D]#^bj kbj]^!4Q8O!PQW!Xbj k36w3L M3L41aQ3L M$;"4T[pu%M %*G$;M$JM--/1<1M}1M1T1TUVXYUY1Z(A. 0/ *5 * 'Qd*hu*& ew)wdvZ`F4F&EII*Udv&)w-2\\:LTYTaTajp-q$QT*) ;:L
4 ;;'(,,,37799++&67;;;BJJTXJYZ[\]^_K:G:M:M:O!:OJCSVZiSi'U;'':O  ! +2+*>h'.9+.Fl+NNPQbPc dZ Z ""23_ cBS $_ k M
 0/ *x% ;:2!s   	LL+
L5LL%AM&L$
:ML*M+L/
=1M.!L5M'M-M?M
ML$M5
M?M
M	r  c                 +  > U R                   R                  nU R                  R                  (       a  SOSnU Vs/ s H  oDS   PM	     nn[        R
                  " U5      nU Vs/ s H  n[        XpR                  5      S   PM     nnU R                  USSSSS9n	[        TOU ]%  U	5      n	U	S	   U	S
   pU R                  b|  [        XU R                  / S9u  pU R                  R                  U
SSS9nU Vs/ s H=  n[        R                  " S[        R                  " U R                   5       S3SU5      PM?     nnU R"                  (       GaL  U R$                  R&                  U R(                  :w  a+  U R+                  5         U R$                  R&                  U l        U R,                  S:X  Gaa  [/        U5      nU R                   R0                  (       a  US S U R2                  2   n[5        U S5         U R6                  R9                  UU R2                  U R:                  U R<                  U R>                  U R@                  c  SOU R@                  U RB                  c  SOU RB                  U RD                  U RF                  U RH                  RJ                  S9
nS S S 5        OS /[M        U5      -  n[O        WSS9n[Q        U R                   RR                  [M        U5      -  U R                   RR                  S-   [M        U5      -  5      nUU   nGO;U R,                  S:X  Ga*  U RF                  (       a  [U        U RF                  S9nOS nSU R:                  U R<                  U R>                  U R@                  c  SOU R@                  U RB                  c  SOU RB                  U RD                  US.nU RH                  RJ                  b%  URW                  U RH                  RJ                  5        [Y        SL0 UD6nU RZ                  S:  aw  [M        U5      n[]        U RZ                  5       Vs/ s H  nS PM     nn[^        R`                  Rc                  UXRd                  S9  U VVs/ s H  nU  H  nUPM     M     nnnOUnUn[5        U S5         U Rf                  R9                  UUSU R                  Ri                  SSS9S9nS S S 5        W VVs/ s H#  nURj                    H  nURl                  PM     M%     nnnU RZ                  S:  aA  [^        R`                  Ro                  U Rd                  S9n[Q        UW-  US-   U-  5      nUU   nW Vs/ s H  n[^        Rp                  " UUS9PM     nn[s        XRt                  S 9n[^        Rv                  " X/SS!9n GOU Rx                  (       Ga  U R                  US"9n!U Rz                  R|                  R~                  n"[        5       (       a  S#U Rz                  R|                  l?        OS$U Rz                  R|                  l?        [5        U S%5         [        U Rz                  U R                   U RH                  R                  S&9 n#[^        R                  " 5          U R                  (       a  [        R                  " U Rz                  SS'9O	[        5          U RH                  R                  (       a   U#R                  [^        R                  5        O:U RH                  R                  (       a  U#R                  [^        R                  5        [^        R                  " 5          U#R                  U!R                  U R                  SS(9nS S S 5        S S S 5        S S S 5        S S S 5        S S S 5        WR                  5        Vs/ s H  nUR                  PM     nnU Vs/ s H  n[^        Rp                  " UUS9PM     nn[s        XRt                  S)S*9nU!R                   Vs/ s H  n[^        Rp                  " UUS9PM     n
n[s        XRt                  SS*9n
[^        Rv                  " X/SS!9n U"U Rz                  R|                  l?        GO[5        U S+5         [        U Rz                  U R                   U RH                  R                  S&9 n#[^        R                  " 5          U R                  (       a  [        R                  " U Rz                  SS'9O	[        5          XsU	S	'   U	S
'   U#R8                  " SL0 U	DU R                  SS,.D6n S S S 5        S S S 5        S S S 5        S S S 5        U
R                  S5      n$W S S 2S U$24   n
U S S 2U$S 24   nXR                  :H  n%[^        R                  " U%R                  S5      4U%R                  S5      [^        R                  US-9n&U%R                  5       R                  SS!9U%R                  SS!9   U&U%R                  SS!9'   [^        R                  " U%R                  S5      US9R                  U%R                  S5      S5      n'U'U&R                  S5      :*  R                  5       n([        UU(R                  5       5       V)V*s/ s H  u  n)n*U)U*   R                  5       PM     n+n)n*U(R                  S5      n,U R                  (       a3  U%R                  SS!9) n-U(U-) R                  S5      R                  5       -  n([^        Rv                  " UU(/SS!9n.UR                  S5      n/US:X  a  U RH                  R                  OU RH                  R                  n0[^        R                  " 5          U R                  U R                  U U.U/U05      u  n1nU1U(-  R                  S5      n2U R                  S:w  a  U R                  b!  U R                  U R                  U U.U/U0S.9u  n3nO_U R                   R                  U R                  5      R                  5          U R                  U R                  U U.U/U0S.9u  n3nS S S 5        OS n3S S S 5        U R                  R                  USS/9n4[        US   5      (       aR  / n5[        UU45       H?  u  n6n7U6S   S0   S1:X  a  U6R                  5       S2   OSn8U5R                  S1U8U7-   S3./5        MA     OU4n5U R                  XU5U+5      n9U9U R                  R                  U5      R                  S5      -  R                  SS!9n:U R                  (       a*  U:R                  U R                  S   U R                  S   S49n:U R                  S:w  a6  W1W3-
  n;U;U(-  R                  S5      n<[        U<5      n<U:U R                  U<-  -
  n:U:R                  SU R2                  5      n=U=R                  SS!9n>U=R                  SS!9n?[^        R                  " U?[^        R                  " U?5      5      n@U=R                  SSS59nAUAU=-
  U R2                  S-
  -  nBUBR                  S5      nBU:UB-
  nCU R                  (       a'  WCUCR                  5       -
  UCR                  5       S6-   -  nC[Q        U R                   RR                  [M        U5      -  U R                   RR                  S-   [M        U5      -  5      nWCR                  5       nDUCU   nCUS:X  ab  U R$                  =R                  U R                   R                  U.R                  5       5      R                  5       R                  5       -  sly        U R$                  R                  /U R                  U   S7'   U R                  S:w  a  W;U(-  R                  5       U(R                  5       R                  S8S99-  nEU R                  U   S:   R                  U R                   R                  UE5      R                  5       R                  5       5        U R                   R                  U,5      nFU R                  U   S;   R                  UFR                  5       R                  5       R                  5       5        U R                  U   S<   R                  UFR                  5       R                  5       R                  5       5        U R                  U   S=   R                  UFR                  5       R                  5       R                  5       5        U R                   R                  U%R                  SS!95      nGUFUG   nHS[M        UH5      [M        UF5      -  -
  nIU R                  U   S>   R                  UI5        [M        UH5      S:X  a  [^        GR                   " SUS9nHU R                  U   S?   R                  WHR                  5       R                  5       R                  5       5        U R                  U   S@   R                  UHR                  5       R                  5       R                  5       5        U R                  U   SA   R                  UHR                  5       R                  5       R                  5       5        G[        U GR                  5       H  u  nJnK[^        R                  " U9S S 2UJ4   5      R                  5       nLU R                  U   SBUK SC3   R                  UL5        G[        U9S S 2UJ4   5      R                  5       nMU R                  U   SBUK SD3   R                  UM5        M     U R                  U   SE   R                  U>R                  5       R                  5       5        U R                  U   SF   R                  U?R                  5       R                  5       5        U R                  U   SG   R                  W@R                  5       R                  5       R                  5       5        U GR                  S   GR                  [/        U5      5        U GR                  SH   GR                  [/        U45      5        G[        U GR                  5       H>  u  nJnNU GR                  SI   UN   GR                  U9S S 2UJ4   R                  5       5        M@     U GR                  SJ   GR                  WDR                  5       5        U
UUU(W2WCSK.nU$ s  snf s  snf s  snf ! , (       d  f       GN&= fs  snf s  snnf ! , (       d  f       GN+= fs  snnf s  snf ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= fs  snf s  snf s  snf ! , (       d  f       GNO= f! , (       d  f       GNY= f! , (       d  f       GNc= f! , (       d  f       GNm= fs  sn*n)f ! , (       d  f       G	N= f! , (       d  f       G	N= f)MNr  r  r  r  TleftFr  r   rk  )protected_tokens)skip_special_tokensclean_up_tokenization_spacesz^(z)+r   r  zvLLM.generatery   r   )
r  nrr  rm  rn  ro  rp  
max_tokensr.  rq  r   )from_processr   r   )regex)r  rr  rm  rn  ro  rp  r  guided_decoding)grouprloo_trainer_lora_model)load_tensors)r   use_tqdmlora_requestr   )padding_valuer~   r  paged_attention
sdpa_pagedztransformers.generate_batch)gather_deepspeed3_params)r  )r2  progress_barr  )r  r  ztransformers.generate)r2  disable_compiler  )r   )r  role	assistantcontent)r  r  )r  r  )r|   keepdimg-C6?
num_tokensr   r  klzcompletions/mean_lengthzcompletions/min_lengthzcompletions/max_lengthzcompletions/clipped_ratioz"completions/mean_terminated_lengthz!completions/min_terminated_lengthz!completions/max_terminated_lengthzrewards/z/meanz/stdr  
reward_stdfrac_reward_zero_stdr  r  r  )
prompt_idsprompt_maskrw  completion_mask	old_logpsr  r   )r  r   rb   rK  r&   deepcopyr;   r  r  r  rf  rT   batch_decoderJ   subescaper  ru  r  global_stepr/  r  rv  r-   r   rg  rH   r!  generaterr  rm  rn  ro  rp  rh  r.  rg   rq  r  r%   slicer*  GuidedDecodingParamsr1  r   r~  r(  rR   r&  all_gather_objectr)  r-  	load_loraoutputs	token_idsget_rankr   rB   r   ro  rs  model_wrappedr   _attn_implementationr4   rV   ri  rn  r7  r   r  r@   r  r   bfloat16r  float16r  generate_batchr   r2  r  generated_tokensrm  r  fulllongr  argmaxr  r   expandr   r   booltolistr   r  r   r   rz  r  r  unwrap_modeldisable_adapterr2   popr   r  r  nansumr  clampr,   viewmeanstdisclose
zeros_liker  clonenum_input_tokens_seenitemr  nanmeanfloatr  r  r  r  r  r>   r  extend)Prf   r  r   r  r  r  original_promptsr  prompts_textprompt_inputsr  r   r  all_prompts_textordered_set_of_promptsrw  process_slicer  rq  r   	orig_sizerC  gathered_promptssublistr  vllm_inputsall_outputsr  ri   local_rank_in_grouptp_sliceidsprompt_completion_idspaged_prompt_inputsprevious_attnunwrapped_modelprompt_lengthis_eoseos_idxsequence_indicesr  rowmask_rowr  completion_lengthstruncated_completionsrk  r   r   old_per_token_logpsr  ref_per_token_logpscompletions_textr  r  r  	bootstrapr  r  per_token_klr  grouped_rewardsmean_grouped_rewardsstd_rewardsis_std_zerogrouped_sum	baselinesr  all_process_advantagesmean_klagg_completion_lengthsagg_terminated_with_eosterm_completion_lengthsclipped_completions_ratior@  r  mean_rewardsstd_func_rewardsr  r  sP                                                                                  rk   r  3_UnslothRLOOTrainer._generate_and_score_completionsB  s     !!((**--w6(./1X;/
  ==1kqrkq`g1';P;PQRZ[kqr--$ . 
 />"/"<mL\>]K!!- 'E)?)?RT'#J  00==TY > L _kk^jVZBFFb4>>)B(C2#FDQ^jLk ===zz%%)?)??((*)-)?)?& ~~)#0#> ##33 .>>UAUAU>U-V**4A)-)9)9)B)B$:"22/3/F/F(,(8(8"&**(,

(:"

)-);#'+'A'A262L2L.2ii.I.I *C * BA '+Vc2B.C%CN "7~TU!V %$$22S\A%%33a73w<G! "0!> :---&:A[A[&\O&*O *.*A*A#'#3#3!ZZ#'::#5R4::$(JJ$6SDJJ"&"<"<'6	%! 99..:%,,TYY-H-HI"0"E3D"E11A5 !$L 1I6;D<Z<Z6['\6[6[$'\%%778H,^k^k7l9I'[9IgSZaSZ9I$'[$ (4$.&t_="&(("3"3KQ`kp  BF  BL  BL  BV  BV  Wp  AE  BV  BF"3  #GK > CN!l+w\c\k\kRX&"2"2\k"2+!l11A5 +0*;*;*D*D4==*D*Y'$%89%DGZ]^G^bkFklH%3H%=N KYY.3ell3v>.NY ?P?PQN$)IIz.JPQ$R!((("&"7"7\"7"J ..55JJM(**AR""))>AM""))>!$(EF+&&(8(8SWS\S\SvSv$NRNbNb''(:(:EJhshuu 99>>#&&u~~6YY^^#&&u}}5))+"1"@"@+55I_I_ns #A #K , v   G  EPDVDVDXYDX&f55DXNYJXY.3ell3v>.NY ?P?P_fgNFYFcFcdFcs%,,s6:FcJdZ7H7HW]^J$)IIz.JPQ$R!=JD%%: "$(?@+&&(8(8SWS\S\SvSv$NRNbNb''(:(:EJhshuuNXKk*M:J,K(7(@(@ )#)7;7M7M_c)% v   A 'OOA.M.q.=./@AJ21mn3DEN  #4#44**fkk!n.AejjY_`%+ZZ\%8%8Q%8%?

q
@Q%R

q
!" <<AvFMMfkkZ[n^`a+w/@/@/CCHHJ LO~_n_s_s_uKvwKv-#xs8}335Kvw -003 **%+ZZAZ%6$6!-2G1G0R0RST0U0Y0Y0[[O K#AqI',,Q/>BgoTYY::SWS\S\SwSw
]]_%)%L%L

%&" ->CCAFI yyC>>--1-T-T-&&#- .U .*' ))66tzzBRRT151X1X JJ1**'1 2Y 2.+Q UT '+#? D  00==nbf=gVAY''K&)'3C&D"
7=bz&7I[7XFJJL3^`	""[YQ[E[$\#]^ 'E +K
  226[Zmn $d&9&9&<&<V&D&N&Nq&QQYY^_Y` !!mm(>(>q(AtG]G]^_G`maG 99.1DDL055b9BB		B.G!,,r4+?+?@.333:%))a)0mmK1A1A+1NO &))a)> ?2t7K7Ka7OP	NN2&	y(
 $$$z'88Z^^=MPT=TUJ **S\9++a/3w<?
 ",!1!1!3.
 7?JJ,,0@0@0G0GHZHZH\0]0a0a0c0h0h0jj,-1ZZ-M-M,NdL) 99#o5::<?R?R?T?Z?Z_b?Z?ccGMM$%,,T-=-=-D-DW-M-U-U-W-\-\-^_ "&!1!1!8!89K!Ld56==>T>Z>Z>\>a>a>c>h>h>jkd45<<=S=Y=Y=[=_=_=a=f=f=hid45<<=S=Y=Y=[=_=_=a=f=f=hi #'"2"2"9"9&***:K"L"89P"Q$%,C(DsKaGb(b$b!d78??@YZ&'1,&+kk!F&C#d@AHHI`IfIfIhImImIoItItIvwd?@GGH_HeHeHgHkHkHmHrHrHtud?@GGH_HeHeHgHkHkHmHrHrHtu $-T-C-C#DA ==)9!Q$)?@EEGLMM$(+;*<E BCJJ<X%&6q!t&<=BBDMM$(+;*<D ABIIJZ[	 $E
 	dH%,,-A-F-F-H-M-M-OPdL)001A1A1C1H1H1JKd23::;;L;L;N;S;S;U;Z;Z;\] 	

8##M,$?@

< ''6F(GH !7!78GAtJJy!$'../?1/E/L/L/NO 9

< ''(>(E(E(GH %&,."$
 i
 0 s. l& BAb (]'[ >= "m Z4 ,+ vu    GF  ZYd vu    A@2 xL UT- _s  AR8%"AR=7AAS3B%AS&AS!AS5AS$*AS6AS<.4AU	"AT78;AT%3BAT	>&AT$AT	,AT%4AT7<AU	AU:AU =AU%14AV %AV;;AU<6,AU*	"AU<*AV2AV : AV2!B(AW
	!AV8*AW
S
ASS$
AS3T
ATTAT	T
AT"TAT%T%
AT4T/AT7T7
AU	UAU	U	
AUU*
AU9U4AU<U<
AVVAVV
AV	VAV V 
AV/V8
AW	WAW
W

AWc                 H    U(       a  [        S5      eU R                  X5      $ )Nz2The RLOOTrainer does not support returning outputs)r   _compute_loss)rf   rb   r  return_outputsnum_items_in_batchs        rk   compute_loss _UnslothRLOOTrainer.compute_loss  s"    QRR!!%00rn   c                 P   US   US   pCUS   US   pe[         R                  " X5/SS9n[         R                  " XF/SS9nUR                  S5      n	U R                  UUUU	SS9u  pX-  R	                  S5      nUS	   nX-
  nUS
   n[         R
                  " U5      n[         R                  " USU R                  -
  SU R                  -   5      nUU-  nUU-  n[         R                  " UU5      * nUR                  5       nU R                  R                  (       a  SOSnX-  R	                  5       UR	                  5       R                  SS9-  nU R                  U   S   R                  U R                  R!                  U5      R#                  5       R%                  5       5        USU R                  -
  :  US:  -  nUSU R                  -   :  US:  -  nUU-  nU R                  R!                  UR'                  5       R                  5       5      nU R                  U   S   R                  UR#                  5       R%                  5       5        U R                  U   S   R                  [)        U5      R%                  5       5        U R                  R!                  UR'                  5       R                  5       5      nU R                  U   S   R                  UR#                  5       R%                  5       5        U R                  U   S   R                  [+        U5      R%                  5       5        U R                  R!                  UR'                  5       R                  5       5      nU R                  U   S   R                  UR#                  5       R%                  5       5        U$ )Nr  r   rw  r  r   r~   T)rp  r  r  r  r  r   r  entropyr   zclip_ratio/low_meanzclip_ratio/low_minzclip_ratio/high_meanzclip_ratio/high_maxzclip_ratio/region_mean)rR   ro  rm  rz  r   expr   r  r  r  r"  rb   rK  r  r   r  r,   r)  r(  r*  r=   r<   )rf   rb   r  r  r   rw  r  r   rk  r   r   ry  rx  r  	log_ratior  coef_1coef_2per_sequence_loss1per_sequence_loss2per_sequence_losslossr  mean_entropyis_low_clippedis_high_clippedis_region_clippedgathered_low_clipgathered_high_clipgathered_clip_ratios                                 rk   r[  !_UnslothRLOOTrainer._compute_loss  s_   "("6}8MK*01A*BFK\D]IIz:B	K#AqI',,Q/ &*%L%L  &M &
" !277:;'	%	 L)
9%VQ)9)9%91t?P?P;PQ#j0#j0"YY'9;MNN %%' **--w6 "388:_=P=P=R=X=X]`=X=aadI&--d.>.>.E.El.S.[.[.].b.b.de !1t'7'7#77JNK!A(9(9$99j1nM*_< ,,33N4H4H4J4O4O4QRd1299:K:S:S:U:Z:Z:\]d0188@Q9R9W9W9YZ!--44_5J5J5L5Q5Q5STd23::;M;U;U;W;\;\;^_d1299&AS:T:Y:Y:[\"..556G6M6M6O6T6T6VWd45<<=P=X=X=Z=_=_=abrn   ignore_keysc                 >   U R                  U5      n[        R                  " 5          U R                  5          U R	                  X5      nS S S 5        WR                  5       R                  5       nS S S 5        WS S 4$ ! , (       d  f       N9= f! , (       d  f       N$= fr  )r  rR   rn  compute_loss_context_managerr^  r"  detach)rf   rb   r  r   rr  ri  s         rk   prediction_step#_UnslothRLOOTrainer.prediction_step  su    %%f-]]_224((7 599;%%'D  T4 54 _s"   BA=
&B=
B	B
Blogs
start_timec           	      *  > U R                   R                  (       a  SOSnU R                  U   R                  5        VVs0 s H  u  pEU[	        U5      [        U5      -  _M     nnnUS:X  a(  UR                  5        VVs0 s H  u  pESU 3U_M     nnn0 UEUEn[        T
U ]  X5        U R                  U   R                  5         U R                  R                  (       Ga  U R                  (       Ga  [        5       (       ab  [        U R                  S   U R                  S   U R                  S   U R                  S   U R                  R                   U R"                  5        U R$                  R&                  (       Ga  SU R$                  R&                  ;   a  [(        R*                  b  S	S Kn[/        U R                  R                   5      /[        U R                  S   5      -  U R                  S   U R                  S   S
.U R                  S   ESU R                  S   0EnUR1                  U5      n	U R2                  (       a  U	R5                  S/S9n	[(        R                  S[(        R7                  U	S905        g g g g g g s  snnf s  snnf )Nr  r  eval_r  r  r  r  wandbr   )stepr  r  	advantage)subsetr  )	dataframe)rb   rK  r  r  r   r  r  logclearr  r   r  r6   rG   r  r  r  r  rg   r9  r|  runpandasr  	DataFramer  drop_duplicatesTable)rf   rx  ry  r  r  valmetricspdtabledfr  s             rk   r  _UnslothRLOOTrainer.log  s2   **--w6<@MM$<O<U<U<WX<W3C3s8++<WX 6>:A--/J/hcse}c)/GJ"$"'"D%d!!#+++0D0D0D ""/JJx(JJ|,JJy)JJ|,JJ**11 yy"""w$))2E2E'E%))J_# !!7!789C

8@T<UU"jj2"&**\": jj+	
  L!9 \\%(00++H:+>B		=%+++*CDE K`'E" 1E+ Y
 Ks   $J	J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  ry   )r=  )	rg   rC  r   r   r  r  create_model_cardr  _save_checkpoint)rf   rb   trialr=  r  s       rk   r  $_UnslothRLOOTrainer._save_checkpoint  sj    99!!)dii22388J//55c:2>J*5 .rn   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.
Nr  unsloth_versionunslothJOB_IDhf_jobsaD              @inproceedings{ahmadian2024back,
                title        = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}},
                author       = {Arash Ahmadian and Chris Cremer and Matthias Gall{'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {"{U}}st{"{u}}n and Sara Hooker},
                year         = 2024,
                booktitle    = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024},
                pages        = {12248--12267},
                publisher    = {Association for Computational Linguistics},
                editor       = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar},
            }
            RLOOz`Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMsz
2402.14740)
base_modelr=  rC  r  r  	wandb_url	comet_urltrainer_nametrainer_citationpaper_titlepaper_idz	README.md)is_world_process_zerore   rb   r   rA   pathisdirr  r  r  r  r  r+  r1  r5  rQ   dedentr.   rC  r8   r|  r  urlr/   savejoinrg   r   )rf   r=  r  r  r  citation
model_cards          rk   r  %_UnslothRLOOTrainer.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%z!

 	TYY%9%9;GHrn   ).r  r/  r  r  rG  r  r  r  r  r  r  r2  r.  r-  r  r  rh  rf  rp  r3  r
  r  r  rg  r  r  r   r  rr  r  r  r  r  r  rj  rm  ro  rn  r)  rs  ru  r!  r}  rv  r~  r  )NNNNNNNN)NNNNNNNNr  )NF)r   N)FN)NNN)5r  r  r  r  r  r5  r	   r  r   r   r  r   r   r   r   r  r   r   r"   tuplerR   r4  	Optimizerlr_schedulerLambdaLRr  rH  r^  r   r[  rh  rI   r   rz  r  r?   r  r  r  r  r   r  r  r  r^  r[  rv  r*  r  r  r  r  r  r  s   @rk   r  r    s   _B J
 .2<@%)CGnrUYmq59jv.2%Q S/)*Q JZ(889	Q
 z"Q  g&> ?@Q uWotCwXgOgIhDh?i%ijkQ #5)@.)P#QRQ $,E2I4PgKh2h,i#jQ D12Q (5;;#8#898EKKD\D\DeDe;ffgQ l+Q Qf1$X<"
(7*; "
w "
H
 
  /  
c8ELL))	*/  / bHT#Y<O  C :  M* M*^ # $S%c0A*B%B C#	c5s*++	,# #J 4  4 lZ4U5<<+<%= =>?Z	c5s*++	,Zx
 1 1
0d PXY]^aYbPc  &FS%Z( &Fhuo &FQU &F &FR/ %)&*,0	FISMFI smFI CcD()	FI FIrn   r  c                   L   ^  \ rS rSrSr              SU 4S jjrSrU =r$ )UnslothRLOOTraineriV  a  
    
Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to
Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs]
(https://huggingface.co/papers/2402.14740).

Example:

```python
from datasets import load_dataset
from trl import RLOOTrainer

dataset = load_dataset("trl-lib/tldr", split="train")
def reward_func(completions, **kwargs):
    # Dummy reward function that rewards completions with more unique letters.
    return [float(len(set(completion))) for completion in completions]
trainer = RLOOTrainer(
    model="Qwen/Qwen2-0.5B-Instruct",
    reward_funcs=reward_func,
    train_dataset=dataset,
)

trainer.train()
```

Args:
    model (`Union[str, PreTrainedModel]`):
        Model to be trained. Can be either:

        - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
          path to a *directory* containing model weights saved using
          [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
          using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
          `args.model_init_kwargs`.
        - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
    reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
        Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
        functions with the prompts and completions and sum the rewards. Can be either:

        - A single reward function, such as:
            - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
            path to a *directory* containing model weights saved using
            [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
            using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
            keyword arguments in `args.model_init_kwargs`.
            - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
            - A custom reward function: The function is provided with the prompts and the generated completions,
              plus any additional columns in the dataset. It should return a list of rewards. Custom reward
              functions can also return `None` when the reward is not applicable to those samples. This is useful
              for multi-task training where different reward functions apply to different types of samples. When a
              reward function returns `None` for a sample, that reward function is excluded from the reward
              calculation for that sample. For more details, see [Using a custom reward
              function](#using-a-custom-reward-function).

              The trainer's state is also passed to the reward function. The trainer's state is an instance of
              [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
              reward function's signature.
        - A list of reward functions, where each item can independently be any of the above types. Mixing different
        types within the list (e.g., a string model ID and a custom reward function) is allowed.
    args ([`RLOOConfig`], *optional*, defaults to `None`):
        Configuration for this trainer. If `None`, a default configuration is used.
    train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
        Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
        ignored. The format of the samples can be either:

        - [Standard](dataset_formats#standard): Each sample contains plain text.
        - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
          and content).
    eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
        Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
    processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`] or `None`, *optional*, defaults to `None`):
        Processing class used to process the data. The padding side must be set to "left". If `None`, the
        processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
        padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
        `tokenizer.eos_token` will be used as the default.
    reward_processing_classes (`Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]`, *optional*, defaults to `None`):
        Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:

        - A single processing class: Used when `reward_funcs` contains only one reward function.
        - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
        If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
        `None`, the tokenizer for the model is automatically loaded using
        [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
        functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
        are ignored.
    callbacks (list of [`~transformers.TrainerCallback`], *optional*, defaults to `None`):
        List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
        in [here](https://huggingface.co/docs/transformers/main_classes/callback).

        If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
        method.
    optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
        A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
        model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
    peft_config ([`~peft.PeftConfig`], *optional*, defaults to `None`):
        PEFT configuration used to wrap the model. If `None`, the model is not wrapped.

    c                 6  > 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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_PRECISIONr   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   r   )__version__z4.45.2z**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!
`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`r   r   r   r  r  r  compute_metricspreprocess_logits_for_metricsUNSLOTH_RETURN_LOGITSmax_seq_lengthrc   r  r  r  r  )UnslothVisionDataCollatorlabelsr   pad_to_multiple_of)mlmmlm_probabilityr  )r  r&  dataset_text_fieldr   dataset_kwargsskip_prepare_datasetrB   )PatchRLStatisticsrloo_trainerparallel_mode_n_gpurb   )rb   r  rg   r  r  r  r  r  r  r   r:  r;  r<  r  rd   neftune_hook_handler\  r  r  r   )?r   r  typer  rA   r+  r  r  r   get_input_embeddingsr  unsloth_zoo.utilsr  rR   r  r  r  r  r   r   rS   r  r[   r   r   r   r  r  localsre   r  rc   r  r  unsloth_zoo.vision_utilsr  r  r\   r  +TransformersDataCollatorForLanguageModelingr&  r  r  unsloth_zoo.logging_utilsr  r^   NOT_DISTRIBUTEDn_gpur  r  r  rd   r  remover\  r  scaleraccelerator_scalerrb   r_   rq   r  r  )(rf   rb   r  rg   r  r  r  r  r  r  r   r:  r;  r<  r  rh   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  _UnslothRLOOTrainer__tokenizerr  other_metricsr  r  current_modelr  s(                                          rk   r  UnslothRLOOTrainer.__init__  s   $ < 1 3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 ?.-8 4$/<3O3OOTXT^T^abTbtXq)Q.fh75.#A#A  	4')'/(A!%'#)	4 -3	4 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rn   )r  )NNNNNNNNNNNNNN)r  r  r  r  r  r  r  r  r  s   @rk   r  r  V  sB    aH $(k krn   r  	addFilterc                        \ rS rSrS rS rSrg)HideLoggingMessageik	  c                     Xl         g r  r  )rf   r  s     rk   r  HideLoggingMessage.__init__l	  s    d)rn   c                 <    U R                   UR                  5       ;  $ r  )r  
getMessage)rf   r  s     rk   filterHideLoggingMessage.filterm	  s    alln)DErn   r  N)r  r  r  r  r  r  r  r   rn   rk   r  r  k	  s    2Ern   r  z`use_cache=True`)zr  rR   r   torch.nnr?   r   Ftypingr   r   r   r   r	   r
   r   r   trl.trainer.rloo_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.   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   rK   rL   rM   rN   rO   rP   rQ   rS   rT   rU   rV   rW   dataclassesrY   rZ   packaging.versionr[   numpynp
contextlibr\   r]   r  transformers.training_argsr^   ro   typesr_   rq   torch_compile_optionscompiler   r  r   r   r   r   r   r  r  re   Filterr  r  r   rn   rk   <module>r     s  0    $ I I I E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E 
  ( %   " $  3      4;PR S"||  \\	&,, %  	
 \\6ell C ELL 
 E	5
 E	5 E	5N xI' xIr+N, N`  6;FW^^ F 	
'(:;<  rn   