Files
DS-LLM-TEMPLATE-FINETUNING/unsloth_compiled_cache/__pycache__/UnslothDPOTrainer.cpython-310.pyc
T

716 lines
73 KiB
Plaintext
Raw Normal View History

2025-08-28 17:57:59 +00:00
o
2025-08-28 22:41:56 +00:00
õ×°hcã@sbdZddlmZddlZddlmZddlmZddlmZm Z m
2025-08-28 17:57:59 +00:00
Z
m Z m Z m
Z
mZmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m
Z
m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m Z m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmZmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmZmOZOmPZPmZm
Z
m$Z$m%Z%m*Z*m=Z=mCZCmZddlCZCddlTddlQm0Z0mRZRdd lSmTZTddlZddlUZVdd
lWmBZBddlmZdd lXmYZYmZZ[d d
d d
d
dœZ\ej]d d e\dddƒZ^e0GdddeƒƒZ_ Gddde*ƒZ`Gddde`ƒZadS)z9
2025.8.9
2025.8.10
4.55.4
0.21.0
__UNSLOTH_VERSIONING__
é)ÚTensorN)Ú
functional)ÚAnyÚListÚOptionalÚTupleÚUnionÚDictÚSetÚCallable)OrÚAutoModelForCausalLMÚ
AutoTokenizerÚBaseImageProcessorr Ú DPOConfigÚ
DPOTrainerÚ DataCollatorÚDataCollatorForPreferenceÚ
DataLoaderÚDatasetÚEvalLoopOutputÚFDivergenceConstantsÚFDivergenceTypeÚFeatureExtractionMixinÚIterableDatasetÚLiteralÚ$MODEL_FOR_VISION_2_SEQ_MAPPING_NAMESrÚ PartialStateÚPathÚ
PeftConfigÚ PeftModelÚPreTrainedModelÚPreTrainedTokenizerBaseÚProcessorMixinÚRunningMomentsÚSyncRefModelCallbackÚTrainerÚTrainerCallbackrÚautocastÚcap_expÚcontextmanagerÚcreate_reference_modelÚ dataclassÚ defaultdictÚdisable_dropout_in_modelÚ empty_cacheÚ
flush_leftÚ flush_rightÚgenerate_model_cardÚget_comet_experiment_urlÚget_peft_modelÚinspectÚis_comet_availableÚis_liger_kernel_availableÚis_mlflow_availableÚis_peft_availableÚis_wandb_availableÚlog_table_to_comet_experimentÚmaybe_apply_chat_templateÚmaybe_extract_promptÚnnÚ nullcontextÚosÚpadÚ
pad_to_lengthÚpdÚpeft_module_casting_to_bf16Úprepare_deepspeedÚ prepare_fsdpÚprepare_model_for_kbit_trainingÚrandomÚselective_log_softmaxÚshift_tokens_rightÚtextwrapÚtorchÚtqdmÚwarningsrrr r!r&r9r@rL)Ú*)r,Úfield)ÚVersion)r?)ÚDataCollatorForSeq2SeqÚDataCollatorForLanguageModelingTF)Úepilogue_fusionÚ max_autotuneÚ
shape_paddingz
trace.enabledztriton.cudagraphs)ÚdynamicÚ fullgraphÚoptionsc
Ctj| d|jd¡ddd}tj| d¡ddd}g}t||ƒD](\}}| tj¡}tj|d| d¡d  d¡}tj
|dd}||} |  | ¡q! t  |¡}| |jd|jdf¡}|S)Néÿÿÿÿér)ÚchunksÚdim)r]Úindex©r]é)
rLÚchunkÚreshapeÚshapeÚzipÚtoÚfloat32ÚgatherÚ unsqueezeÚsqueezeÚ logsumexpÚappendÚconcat)
Úlogitsr^Úchunked_logitsÚ
chunked_indexÚall_per_token_logpsÚ chunk_logitsÚ chunk_indexÚselected_logitsÚlogsumexp_valuesÚper_token_logps©rvúQ/workspace/DS-LLM-TEMPLATE-FINETUNING/unsloth_compiled_cache/UnslothDPOTrainer.pyÚchunked_selective_log_softmax"s  
rxceZdZUdZedddidZeeed<edddidZ ee
ed <eddd
idZ ee
ed <  
                            ! ! " #     $           $      % &  '         (      #    $   ) *              + ,  - .   /   %   0  1 ,   d4‡fd2d3„ Z Z
S)5ÚUnslothDPOConfigu6.
Configuration class for the [`DPOTrainer`].
This class includes only the parameters that are specific to DPO 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 (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the
[`DPOTrainer`] is provided as a string.
ref_model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`):
Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `ref_model` argument of the
[`DPOTrainer`] is provided as a string.
model_adapter_name (`str` or `None`, *optional*, defaults to `None`):
Name of the train target PEFT adapter, when using LoRA with multiple adapters.
ref_adapter_name (`str` or `None`, *optional*, defaults to `None`):
Name of the reference PEFT adapter, when using LoRA with multiple adapters.
force_use_ref_model (`bool`, *optional*, defaults to `False`):
If you provide a PEFT model as the active model and wish to use a different model for the `ref_model`, set
this flag to `True`.
disable_dropout (`bool`, *optional*, defaults to `True`):
Whether to disable dropout in the model and reference model.
use_logits_to_keep (`bool`, *optional*, defaults to `False`):
If `True`, only a specified number of logits are computed in the forward pass. This can be useful for
saving memory and speeding up training by not computing the logits for all tokens, especially in scenarios
when working with very long prompts where labels are ignored (-100).
> Parameters that control the data preprocessing
dataset_num_proc (`int` or `None`, *optional*, defaults to `None`):
Number of processes to use for processing the dataset.
padding_value (`int` or `None`, *optional*, defaults to `None`):
Padding value to use. If `None`, the padding value of the tokenizer is used.
label_pad_token_id (`int`, *optional*, defaults to `-100`):
Padding value to use for labels.
max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
Maximum length of the prompt.
max_completion_length (`int` or `None`, *optional*, defaults to `None`):
Maximum length of the completion.
max_length (`int` or `None`, *optional*, defaults to `1024`):
Maximum length of the full sequence (prompt + completion).
truncation_mode (`str`, *optional*, defaults to `"keep_end"`):
Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_end"` and
`"keep_start"`.
padding_free (`bool`, *optional*, defaults to `False`):
Whether to perform forward passes without padding by flattening all sequences in the batch into a single
continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only
supported with the `flash_attention_2` attention implementation, which can efficiently handle the flattened
batch structure.
precompute_ref_log_probs (`bool`, *optional*, defaults to `False`):
Whether to precompute the log probabilities from the reference model. Setting this to `True` allows
training without needing the reference model during training, which can help reduce GPU memory usage. If
set to `False` (default), the reference model will be used during training to compute log probabilities
on-the-fly.
precompute_ref_batch_size (`int` or `None`, *optional*, defaults to `None`):
Batch size to use when precomputing reference model log probabilities. This can be set higher than the
training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for
training and `per_device_eval_batch_size` for evaluation.
tools (`Optional[list[Union[dict, Callable]]]`, *optional*, defaults to `None`):
List of tools (callable functions) that will be accessible to the model. If the template does not support
function calling, this argument will have no effect.
> Parameters that control the training
loss_type (`str` or `list[str]`, *optional*, defaults to `"sigmoid"`):
Type of loss to use. Possible values are:
- `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
- `"hinge"`: hinge loss on the normalized likelihood from the
[SLiC](https://huggingface.co/papers/2305.10425) paper.
- `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
- `"exo_pair"`: pairwise EXO loss from the [EXO](https://huggingface.co/papers/2402.00856) paper.
- `"nca_pair"`: pairwise NCA loss from the [NCA](https://huggingface.co/papers/2402.05369) paper.
- `"robust"`: unbiased estimate of the DPO loss that is robust to preference noise from the [Robust
DPO](https://huggingface.co/papers/2403.00409) paper.
- `"bco_pair"`: pairwise BCO loss from the [BCO](https://huggingface.co/papers/2404.04656) paper.
- `"sppo_hard"`: SPPO loss with hard label from the [SPPO](https://huggingface.co/papers/2405.00675)
paper.
- `"aot"`: AOT loss for paired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper.
- `"aot_pair"`: AOT loss for unpaired datasets from the [AOT](https://huggingface.co/papers/2406.05882)
paper.
- `"discopop"`: DiscoPOP (a.k.a Log-Ratio Modulated Loss, LRML) loss from the
[DiscoPOP](https://huggingface.co/papers/2406.08414) paper.
- `"apo_zero"`: APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
- `"apo_down"`: APO-down loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
- `"sft"`: Negative log-likelihood loss (standard supervised fine-tuning loss).
Multiple loss types can be combined using comma separation (e.g., `["sigmoid", "bco_pair", "sft"]` for
[MPO](https://huggingface.co/papers/2411.10442)). The `loss_weights` parameter can be used to specify
corresponding weights for each loss type.
use_liger_loss (`bool`, *optional*, defaults to `False`):
Whether to use Liger loss.
base_model_attribute_name (`str`, *optional*, defaults to `"model"`):
Name of the attribute in the model that contains the base model. This is used to get the base model from
the model when the model does not have a `get_decoder` method in the case when `use_liger_loss` is `True`.
beta (`float`, *optional*, defaults to `0.1`):
Parameter controlling the deviation from the reference model. Higher β means less deviation from the
reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in
the [paper](https://huggingface.co/papers/2310.12036).
f_divergence_type (`str`, *optional*, defaults to `FDivergenceType.REVERSE_KL`):
Type of f-divergence regularization function to compute divergence between policy and reference model.
f_alpha_divergence_coef (`float`, *optional*, defaults to `1.0`):
α coefficient in the α-divergence u^-α regularization function for DPO loss.
reference_free (`bool`, *optional*, defaults to `False`):
Whether to ignore the provided reference model and implicitly use a reference model that assigns equal
probability to all responses.
label_smoothing (`float`, *optional*, defaults to `0.0`):
Robust DPO label smoothing parameter from the [cDPO report](https://ericmitchell.ai/cdpo.pdf) and [Robust
DPO](https://huggingface.co/papers/2403.00409) paper that should be between `0.0` and `0.5`.
use_weighting (`bool`, *optional*, defaults to `False`):
Whether to weight the loss as done in the [WPO paper](https://huggingface.co/papers/2406.11827).
rpo_alpha (`float`, *optional*, defaults to `None`):
α parameter from the [RPO paper](https://huggingface.co/papers/2404.19733) (v3), which controls the
weighting of the NLL term in the loss. If `None`, no weighting is applied and the loss is the same as the
DPO loss. The paper recommends `rpo_alpha=1.0`.
ld_alpha (`float` or `None`, *optional*, defaults to `None`):
α parameter from the [LD-DPO paper](https://huggingface.co/papers/2409.06411), which controls the weighting
of the verbose token log-probabilities in responses. If `None`, no weighting is applied to the verbose
part, and the loss is equivalent to the standard DPO loss. The paper recommends setting `ld_alpha` between
`0.0` and `1.0`.
discopop_tau (`float`, *optional*, defaults to `0.05`):
Ï„/temperature parameter from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper, which controls
the shape of log ratio modulated loss. The paper recommends the default value `discopop_tau=0.05`.
loss_weights (`list[float]` or `None`, *optional*, defaults to `None`):
List of loss weights for multi-loss combinations. Used when combining multiple loss types.
Example: `[0.8, 0.2, 1.0]` for [MPO](https://huggingface.co/papers/2411.10442). If not provided, defaults
to equal weights (`1.0`) for all loss types.
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
generate_during_eval (`bool`, *optional*, defaults to `False`):
Whether to generate and log completions from both the model and the reference model to W&B or Comet during
evaluation.
helpzvLLM SamplingParams)ÚdefaultÚmetadataÚvllm_sampling_paramsrZz8Chunk size to reduce memory usage. -1 is most efficient.Úunsloth_num_chunksz'Maximum sequence length to truncate to.Úmax_seq_lengthFÚnor[éréúç-Cëâ6
?ç{®Gáz„?çÍÌÌÌÌÌì?ç+‡ÙÎ÷ï?ç:Œ0âŽyE>çð?çlinearçš™™™™™¹?ÚpassiveÚwarningTÚstepsr`éôéO
ÚO1ÚautoÚçÚ
adamw_8bitÚlengthÚ
every_saveÚlastééœÿÿÿééÚkeep_endÚmodelçš™™™™™©?ç333333ã?c¥§ sb|dkr td|dƒ|dkrtd|dƒ|dur(|#dkr(|$dkr(d}d }#|ˆdur:d
d lmt|¦ƒd d
ƒ}ˆtƒjd¯id|d|d|d|d|d|d|d|d| “d|
d| d| d|
d|d|d|d|d|d |d!|d"|d#|d$|d%|d&|d'|d(|d)|d*|d+|d,|d-| “d.|!“d/|"“d0|#“d1|$“d2|%“d3|&“d4|'“d5|(“d6|)“d7|*“d8|+“d9|,“d:|-“d;|.“d<|/“d=|0“d>|1“d?|2“d@|3“dA|4“dB|5“dC|6“dD|7“dE|8“dF|9“dG|:“dH|;“dI|<“dJ|=“dK|>“dL|?“dM|@“dN|A“dO|B“dP|C“dQ|D“dR|E“dS|F“dT|G“dU|H“dV|I“dW|J“dX|K“dY|L“dZ|M“d[|N“d\|O“d]|P“d^|Q“d_|R“d`|S“da|T“db|U“dc|V“dd|W“de|X“df|Y“dg|Z“dh|[“di|\“dj|]“dk|^“dl|_“dm|`“dn|a“do|b“dp|c“dq|d“dr|e“ds|f“dt|g“du|h“dv|i“dw|j“dx|k“dy|l“dz|m“d{|n“d||o“d}|p“d~|q“d|r“d€|s“d|t“d|u“dƒ|v“d„|w“d…|x“d†|y“d‡|z“dˆ|{“d‰||“dŠ|}“d|~“dŒ|d|€“dŽ|d|‚“d|ƒ“d‘|„“d’|…“d“|†“d”|‡“d•|ˆ“d–|‰“d—|Š“d˜|‹“d™|Œ“dš|d›|Ž“dœ|d|dž|‘“dŸ|’“d |““d¡|”“d¢|•“d£|–“d¤|—“d¥|˜“d¦|™“d§|š“d¨|›“d©|œ“dª|d«|ž“d¬|Ÿ“d­| “d®|¡“|¥¤Ž|¢|_|£|_|¤|_ dS)°NgH¯¼šò×z>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_countr[rÚ
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Ú 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Úref_model_init_kwargsÚmodel_adapter_nameÚref_adapter_nameÚforce_use_ref_modelÚdisable_dropoutÚuse_logits_to_keepÚdataset_num_procÚ
padding_valueÚlabel_pad_token_idÚmax_prompt_lengthÚmax_completion_lengthÚ
max_lengthÚtruncation_modeÚ padding_freeÚprecompute_ref_log_probsÚprecompute_ref_batch_sizeÚtoolsÚuse_liger_lossÚbase_model_attribute_nameÚbetaÚf_alpha_divergence_coefÚreference_freeÚlabel_smoothingÚ
use_weightingÚ rpo_alphaÚld_alphaÚ discopop_tauÚ loss_weightsÚsync_ref_modelÚref_model_mixup_alphaÚref_model_sync_stepsÚgenerate_during_evalrv)
ÚFloatingPointErrorÚ
OverflowErrorÚmultiprocessingr¢ÚmaxÚsuperÚ__init__r}r~r)§Úselfr£r­r¿rÿrrrrrrrrrr r
r r r
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>r?r@rArBrCr}r~rÚkwargsr¢©Ú __class__rvrwrIÞs()  ÿþýüûúùø ÷
ö õ ô
óòñðïîíìëêéèçæåäãâá à!ß"Þ#Ý$Ü%Û&Ú'Ù(Ø)×*Ö+Õ,Ô-Ó.Ò/Ñ0Ð1Ï2Î3Í4Ì5Ë6Ê7É8È9Ç:Æ;Å<Ä=Ã>Â?Á@ÀA¿B¾C½D¼E»FºG¹H¸I·JKµL´M³N²O±P°Q¯R®S­T¬U«VªW©X¨Y§Z¦[¥\¤]£^¢_¡` aŸbžcdœefšgh˜ijklmnopqrŽstŒuvŠwxˆyz{|}ƒ~ÿþýüûúùø ÷
ö õ ô
óòñðïîíìëêéèçæåäãâá à!ß"Þ#
zUnslothDPOConfig.__init__)¤NNFFFr€Fr[r[NNrrrrr„r…r†r‡rˆr‰rZrrrTNrŽFr`FrŽrNTFFFFFFrrFFFFrrFFNrZNNFr“FNrNrZNNTNFNNFr“rNNNNr”r•NFFrNNNNTFTFFNNr—NNFNFNFTrNNNr“TFNr˜r™FNNFFNNFFFNFTNNNNFTFNNršrNrœrFFNNFržrrˆFr”FNNrŸNFr rFNrZN)Ú__name__Ú
__module__Ú __qualname__Ú__doc__rPr}rrÚ__annotations__r~ÚintrrIÚ
__classcell__rvrvrLrwry3sj
þþþÚrycs eZdZdZddgZ            djdeeeje fde
ee ejefde
e d e
e d
e
ee
efd e
ee
eeeee
efffd e
eeeeefd
e
eegefde
eedee
ejje
ejjjfde
eeejjeeeffde
eej ej gej fde
dffdd
Z!dkdede de"de fddZ#de de dede de f
ddZ$de de fddZ%d ee
efd eeeeefde d!edee
eff
d"d#„Z&e'   $dld%eeefd ed&e
e(d'e
e(d(e"deeee(ff d)d*„ƒZ)e'   $dld%eeefd ed&e
e(d'e
e(d(e"deeee(ff d+d,„ƒZ*d-d.„Z+de,ffd/d0„ Z-dmd e
e
de,ffd1d2„
Z.e/d3d4„ƒZ0d5eeej1fdeej ej ffd6d7„Z2e'd5eeeeej1ffd8e(deeej1ffd9d:„ƒZ3 ; dnd<ej4d=ej4d>ej4d?ej4d@edAeeej4fdeej4ej4ej4ffdBdC„Z5dejd5eeeeej1ffdeeej ffdDdE„Z6 dkdejd5eeeeej1ffdFe"deeej ffdGdH„Z7 Idodee ejfd5eeeeej1ffdJe8dKdeej eee9fffdLdM„Z:  dpdee ejfdNeeeej effdeej eej eee9ffffdOdP„Z;d5eeej1fdeeeffdQdR„Z< dmdee ejfdNeeeej effdSe"dTe
eedeej e
ej e
ej ff
dUdV„Z=dodWeee9fdJe8dKddfdXdY„Z>   Zdqd[e,d\edSe
e"dTe
eed]edef fd^d_„
Z?dmd`eee9fdae
e9ddffdbdc„
Z@‡fddde„ZA   drdfe
ed!e
edgeeeedffdhdi„ZB‡ZCS)sÚ_UnslothDPOTrainerr“ÚtrlÚdpoN©NNržÚ ref_modelÚargsÚ
data_collatorÚ
train_datasetÚ eval_datasetÚprocessing_classÚcompute_metricsÚ callbacksÚ
optimizersÚoptimizer_cls_and_kwargsÚpreprocess_logits_for_metricsÚ peft_configrc
stt|tƒr|n|jj}ˆdur| d¡d}t|dƒˆdur&t |¡ˆjdur0ˆjˆ_n$t ˆdƒr?ˆj
dur?ˆj
ˆ_nt ˆdƒrPˆj j
durPˆj j
ˆ_nt dƒt|tƒsa||urat dƒˆj
durpt|tƒspt d¡t|tƒr{ˆ |ˆ¡}ˆjdurŠt|tƒsŠt d ¡t|tƒr—ˆj|ˆd
d }ˆ |||
ˆ¡}ˆjr¯tƒs¯tƒs¯tƒs¯t d ƒ|jjˆ_|jjt ¡vˆ_tƒoÄt|tƒˆ_ˆjˆ_ˆj ˆ_ ˆj!ˆ_!|rØ|ˆ_"nˆjsÞˆj#râdˆ_"nt$|ƒˆ_"ˆj%røt&|ƒˆj"durøt&ˆj"ƒˆj'rt(ƒst)d
ƒˆj*dkrt dƒt+ˆj,ˆj-ˆj! ddˆ_.d
|j/d<|dur+t0ˆjd}ˆjˆ_ˆj,ˆ_,ˆj1ˆ_1ˆj2ˆ_2ˆj3ˆ_3ˆj4ˆ_4ˆj#ˆ_#ˆj5ˆ_5ˆj6rf|jj7dkr[t d¡ˆj8dkrft d¡ˆj6ˆ_6dˆ_9dˆ_:ˆj-ˆ_-ˆj;ˆ_;tˆj*t<ƒr‚ˆj*nˆj*gˆ_*ˆj=ˆ_=t>|jddƒˆ_?ˆj@ˆ_@t>|jddƒˆ_Aˆj?r¯ˆjAdkr¯t dtB¡ˆj*D]!}|dvrɈj;dkrÉt d|dtB¡|d krÒt d!ƒq²tCd"d#„ƒˆ_DˆjEˆ_EtFjGˆjHiˆ_IˆjJˆ_Jˆ K|ˆˆd$¡}|durt|tLƒr fd%d&„| Dƒ}nˆ K|ˆˆd'¡}tNƒjO|ˆ|||ˆ|| |
| | d( dˆ_Pt ˆjQd)ƒr5ˆjQ RˆjS¡t ˆd*ƒs?tTd+ƒˆjUrTˆjVjWjXjYd,krTˆj#rTt d-ƒˆj"duroˆjsfˆj#sft d.ƒˆjZrnt d/ƒn$ˆjUr|t[ˆj"ˆjVƒˆ_"nˆj\r‰t]ˆj"ˆjVƒˆ_"n
ˆjVj^ˆj"d
d0ˆ_"ˆjZrªˆj#rŸt d1ƒˆ _t`ˆj"ˆjVd2¡d3ˆj*vr¸taˆjVƒˆ_bdSdS)4Nú/rZz-DPOÚ pad_token_idÚ tokenizera`padding_value` is not specified in `DPOConfig`, and `pad_token_id` is missing in the `processing_class`. Please either set the `padding_value` argument in `DPOConfig`, or set `tokenizer.pad_token` (e.g., `tokenizer.pad_token = tokenizer.eos_token`) before instantiating the trainer.zœ`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the same as `model`, you must mass a copy of it, or `None` if you use peft.zYou passed model_init_kwargs to the `DPOConfig`, but your model is already instantiated. The `model_init_kwargs` will be ignored.zYou passed ref_model_init_kwargs to the `DPOConfig`, but your ref_model is already instantiated. The `ref_model_init_kwargs` will be ignored.T)Úis_refz”`generate_during_eval=True` requires Weights and Biases, MLFlow or Comet to be installed. Please install `wandb`, `mlflow` or `comet-ml` to resolve.zYou set `use_liger_loss=True` but the liger kernel is not available. Please install liger-kernel first: `pip install liger-kernel`Úsigmoidz{You set `use_liger_loss=True` but the loss type is not `sigmoid`. Please set `loss_type='sigmoid'` to use the liger kernel.F)Ú ignore_indexr7Ú
use_ref_modelÚaverage_log_probÚestimate_tokens)rfÚflash_attention_2açPadding-free training is enabled, but the attention implementation is not set to 'flash_attention_2'. Padding-free training flattens batches into a single sequence, and 'flash_attention_2' is the only known attention mechanism that reliably supports this. Using other implementations may lead to unexpected behavior. To ensure compatibility, set `attn_implementation='flash_attention_2'` in the model configuration, or verify that your attention mechanism can handle flattened sequences.r`zÎYou are using a per_device_train_batch_size of 1 with padding-free training. Using a batch size of 1 anihilate the benefits of padding-free training. Please consider increasing the batch size to at least 2.Úoutput_router_logitsÚrouter_aux_loss_coefr”a-You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to `0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary loss.)ÚhingeÚipoÚbco_pairÚ sppo_hardÚnca_pairÚapo_zeroÚapo_downrzYou are using the z™ loss type that does not support label smoothing. The `label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning.Úkto_pairzKSupport for kto_pair has been removed in DPOTrainer. Please use KTOTrainer.cSsttƒS©N)r-ÚlistrvrvrvrwÚ<lambda>ösz-_UnslothDPOTrainer.__init__.<locals>.<lambda>Útrainc s"i|]
\}}|ˆ |ˆˆ|¡qSrv)Ú_prepare_dataset)Ú.0ÚkeyÚdataset©rZr^rJrvrwÚ
<dictcomp>ÿsÿÿz/_UnslothDPOTrainer.__init__.<locals>.<dictcomp>Úeval) rZr[r\r]r^r_r`rarbrcÚadd_model_tagsÚ acceleratorzXYour `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`.ézrYou cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`.z]No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`zYYou currently cannot use `ref_model=None` with TR-DPO method. Please provide `ref_model`.)Úevaluation_modezoYou cannot use `precompute_ref_log_probs=True` with TR-DPO method. Please set `precompute_ref_log_probs=False`.)rYr…rs)cÚ
isinstanceÚstrÚconfigÚ
_name_or_pathÚsplitrr
Úfrom_pretrainedr+ÚhasattrrfrgÚ
ValueErrorr#rNÚwarnÚ_create_model_from_pathr$Ú_prepare_peft_modelrCr:r6r8Úis_encoder_decoderÚ
model_typerÚkeysÚis_vision_modelr9r Ú
is_peft_modelr%r&r9rYr2r+r(r.r5r7Ú ImportErrorÚ loss_typeÚLigerFusedLinearDPOLossr,r7Ú dpo_loss_fnÚwarnings_issuedrr-r.r/r0r)r1Ú_attn_implementationrªÚ _precomputed_train_ref_log_probsÚ_precomputed_eval_ref_log_probsr:rzr?ÚgetattrÚaux_loss_enabledr;Ú
aux_loss_coefÚ UserWarningr-Ú_stored_metricsÚf_divergence_typerÚALPHA_DIVERGENCE_COEF_KEYr8Úf_divergence_paramsr*r}ÚdictÚitemsrHrIÚmodel_accepts_loss_kwargsržr„Ú
_tag_namesÚAttributeErrorÚis_deepspeed_enabledr…ÚstateÚdeepspeed_pluginÚ
zero_stager@rEÚis_fsdp_enabledrFÚ
prepare_modelÚ add_callbackr%r$Úrunning)rJrYrZr[r\r]r^r_r`rarbrcrdÚmodel_idÚ
model_namer™rLrrwrI;sV



 ÿÿÿ
 ÿ
ÿ
 


ÿ ÿü
 ÿ ÿû

 
ý
ÿ
 þõ ÿÿ ÿÿÿÿ ÿz_UnslothDPOTrainer.__init__FÚ
model_pathrhÚreturncCs†|s|jpi}n|jp i}| d¡}t|tjƒs |dks |dur!nt|tƒr0tt|ƒ}||d<ntd|dƒt j
|fi|¤Ž}|S)z0Creates a model from a path or model identifier.Ú torch_dtyperNzˆInvalid `torch_dtype` passed to `DPOConfig`. Expected either 'auto' or a string representing a `torch.dtype` (e.g., 'float32'), but got Ú.) r#r$ÚgetrˆrLÚdtyper‰r rr r)rJrZrhr#rvrvrwrEs  




ÿÿ z*_UnslothDPOTrainer._create_model_from_pathcCd|_tƒs|durtdƒtƒrv|durvt|tƒr| ¡}|dur)|js)tdƒt|ddƒs5t|ddƒrYt|dƒoCdt t
  t ¡j
ƒv}d|ji}|rP|j|d<t |fi|¤Ž}n| ||¡}t||ƒ}|jrtt|ddƒrtt|ƒd |_|S| ||¡}|S)
z#Prepares a model for PEFT training.FNzvPEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT modelsa8You passed both a ref_model and a peft_config. For training PEFT adapters with DPO there is no need to pass a reference model. Please pass `ref_model=None` in case you want to train PEFT adapters, or pass a ref_model with `force_use_ref_model=True` in DPOTrainer's init. if you want to use a different ref_model.Úis_loaded_in_8bitÚis_loaded_in_4bitr Úuse_gradient_checkpointingT)Ú_peft_has_been_casted_to_bf16r9rrˆr Úmerge_and_unloadr'r rzr5Ú signaturerGÚ
parametersrr Ú_prepare_gradient_checkpointingr4rD)rJrYrdrZÚ_support_gc_kwargsÚprepare_model_kwargsrvrvrwr`s@ÿ
ÿÿ
ÿþ

 
 þz&_UnslothDPOTrainer._prepare_peft_modelcCs6|jrt|dƒr| ¡|Sdd}| ¡ |¡|S)z4Prepare the gradienting checkpointing for the model.Úenable_input_require_gradscSs| d¡dS)NT)Úrequires_grad_)ÚmoduleÚinputÚoutputrvrvrwÚmake_inputs_require_grad szT_UnslothDPOTrainer._prepare_gradient_checkpointing.<locals>.make_inputs_require_grad)rÚget_input_embeddingsÚregister_forward_hook)rJrZrvrvrws
ûz2_UnslothDPOTrainer._prepare_gradient_checkpointingr€Ú dataset_namec Csi}t|tƒr|j|d<d|d<tƒ ¡dt|tƒr#d|d|d<|jtfi|¤Ž}t|tƒr9d|d|d<|jtfd||jd œi|¤Ž}t|tƒrUd
|d|d<|j|j s]|j
n|j fd d g||j |j
d
dœdœ|¤Ž}Wdƒ|S1s|wY|S)num_procé
Úwriter_batch_sizezExtracting prompt in z datasetÚdesczApplying chat template to Ú fn_kwargs)rgr4z Tokenizing ÚchosenÚrejectedF)r^r-r.Úadd_special_tokens)Úremove_columnsrÔ)rˆrr*rÚmain_process_firstÚmapr=r<r4rÚ tokenize_rowÚ process_rowr-r.)rJr€r^rZÚ
map_kwargsrvrvrwr}§sF

 

ÿ
ÿÿ
ÿûý
ö
ïâz#_UnslothDPOTrainer._prepare_datasetTÚfeaturesr-r.r×c C|}||dddd}||dddd}||dddd}|r8|jdur-|jg|}|jdur8||jg}||jg}||jg}|durO|| d}|dur_|d|}|d|}|||dœS) a©
Tokenize a row of the dataset.
Args:
features (`dict[str, str]`):
Row of the dataset, should contain the keys `"prompt"`, `"chosen"`, and `"rejected"`.
processing_class (`PreTrainedTokenizerBase`):
Processing class used to process the data.
max_prompt_length (`int` or `None`):
Maximum length of the prompt sequence. If `None`, the prompt sequence is not truncated.
max_completion_length (`int` or `None`):
Maximum length of the completion sequences. If `None`, the completion sequences are not truncated.
add_special_tokens (`bool`):
Whether to add special tokens to the sequences. Typically used for encoder-decoder models. If `True`,
the prompt sequence will have a bos token prepended and an eos token appended. In any case, the
completion sequences will have an eos token appended.
Returns:
`dict[str, list[int]]`:
Tokenized sequences with the keys `"prompt_input_ids"`, `"chosen_input_ids"`, and
`"rejected_input_ids".
Example:
```python
>>> from transformers import GPT2Tokenizer
>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"}
>>> DPOTrainer.tokenize_row(
... features, tokenizer, max_prompt_length=3, max_completion_length=3, add_special_tokens=False
... )
{'prompt_input_ids': [464, 6766, 318], 'chosen_input_ids': [4171, 50256], 'rejected_input_ids': [4077, 50256]}
```
ÚpromptF©r×Ú input_idsrÕN)Úprompt_input_idsÚchosen_input_idsÚrejected_input_ids)Ú bos_token_idÚ eos_token_id) rÞr^r-r.r×rgrvrvrwÔs(*
 
     ýz_UnslothDPOTrainer.tokenize_rowc
Cs"||j}}||d|ddd}|dd}|dd} ||ddd d}
||d
dd d} |rI|jd ur>|jg|}|jd urI||jg}|
|jg}
| |jg} |d ur`|| d }|d urp|
d |}
| d |} || |
| d œ} d
|vrƒ|d
d| d
<d|vr|dd| d<| S)zt
Same as `tokenize_row` but for vision models. Please refer to `tokenize_row` for more information.
ÚimagesrßF)Útextr×rÚ pixel_valuesrÕN)Úpixel_attention_maskÚ image_sizes)rg)
r^r-r.r×Ú processorrgÚprocessed_featuresrârvrvrws8   
 
     üz_UnslothDPOTrainer.process_rowcCs|jdur gd¢|_dSdS)N)Úref_chosen_logpsÚref_rejected_logps)Ú_signature_columns©rJrvrvrwÚ _set_signature_columns_if_neededJs
ÿz3_UnslothDPOTrainer._set_signature_columns_if_neededc s|jrƒ|jsƒ|jjp
|jj}||j|jj|jjddœ}|j  t
|j fi|¤Ž¡}g}g}t |ddD])}| 
|¡\}}|j ||f¡\}}| | ¡¡| | ¡¡tƒ|j ¡q2t |¡ ¡ ¡} t |¡ ¡ ¡}
|j jd| d|_ |j jd|
d|_ d|_tƒ ¡S) z·
Returns the training [`~torch.utils.data.DataLoader`].
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
Ú
batch_sizeÚ
collate_fnÚ num_workersÚ
pin_memoryÚshufflez!Train dataset reference log probs©ÚiterablerÓ©ÚnameÚcolumnrïT)r2rZr3r[r…Úpreparerr\rMÚcompute_ref_log_probsÚgather_for_metricsrkÚcpur/Ú free_memoryrLÚcatÚfloatÚnumpyÚ
add_columnrHÚget_train_dataloader) rJÚdataloader_paramsÚ data_loaderrîÚ padded_batchÚref_chosen_logpÚref_rejected_logpÚall_ref_chosen_logpsÚall_ref_rejected_logpsrLrvrwrYs8 û ÿ ÿ
z'_UnslothDPOTrainer.get_train_dataloaderc s6|dur
|jdur
tdƒ|dur|n|j}|jr”|js”|jjp#|jj}||j|jj|jj ddœ}|j
  t |fi|¤Ž¡}g}g}t
|ddD]!}| |¡\}} |j
 || f¡\}} | | ¡¡| |  ¡¡qGt |¡ ¡ ¡}
t |¡ ¡ ¡} |jd|
d}|jd | d}|jdur||_d
|_tƒj|d S) 
Returns the evaluation [`~torch.utils.data.DataLoader`].
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.
Args:
eval_dataset (`torch.utils.data.Dataset`, *optional*):
If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
by the `model.forward()` method are automatically removed. It must implement `__len__`.
Nz-Trainer: evaluation requires an eval_dataset.Fróz Eval dataset reference log probsrùT)r])r]rr2rZr3r[r…rrMrÿrrkrrLrrrrrHÚget_eval_dataloader) rJr]rr r
r r r
rrLrvrwrs:  û ÿ
z&_UnslothDPOTrainer.get_eval_dataloadercc|jr|js|j |j¡ ¡ntƒ*|jr|j |j¡dV|jr5|j |jp+d¡WdƒdSWdƒdS1s@wYdS)zWContext manager for handling null reference model (that is, peft adapter manipulation).Nr{) r—r&r…Ú unwrap_modelržÚdisable_adapterr?Ú set_adapterr%rvrvrwÚnull_ref_contextºsÿÿý÷"øz#_UnslothDPOTrainer.null_ref_contextÚbatchc
C|jr
t|jjjƒntƒ}t ¡F|4|jdur8|  ¡|j
|j |dd}Wdƒn1s2wYn |j
|j|dd}Wdƒn1sKwYWdƒn1sZwY|d|dfS)zfComputes log probabilities of the reference model for a single padded batch of a DPO specific dataset.NT)Ú is_ref_modelÚ chosen_logpsÚrejected_logps) r(r…ÚdeviceÚtyper?rLÚno_gradrYrÚconcatenated_forwardrž)rJrÚcompte_ref_context_managerÚref_model_outputrvrvrwrÿÈsÿ

ÿûz(_UnslothDPOTrainer.compute_ref_log_probsr+cCs0i}tj|d|dgdd|d<tj|d|dgdd|d<d|vr3tj|d|dgdd|d<d|vrFtj|d|dgdd|d<d|vrYtj|d|dgdd|d<t|djd |d
jd ƒ}t t|d||d t|d
||d f¡|d <t t|d
|dd t|d|dd f¡|d<|S)
Concatenate the `chosen` and `rejected` inputs from the batch into a single tensor for both the prompt and
completion sequences.
Args:
batch (`dict[str, Union[list, torch.LongTensor]]`):
A batch of input data. The batch must contain the following keys:
- `"prompt_input_ids"`: Tensor of shape `(batch_size, prompt_length)` representing the prompt input
IDs.
- `"chosen_input_ids"`: Tensor of shape `(batch_size, chosen_length)` representing the chosen
completion input IDs.
- `"rejected_input_ids"`: Tensor of shape `(batch_size, rejected_length)` representing the rejected
completion input IDs.
- `"prompt_pixel_values"` (optional): Tensor for pixel values, if available.
- `"prompt_pixel_attention_mask"` (optional): Tensor for pixel attention masks, if available.
padding_value (`int`):
The padding value to use for the concatenated completion sequences (`chosen_input_ids` and
`rejected_input_ids`).
Returns:
`dict[str, torch.LongTensor]`: A dictionary containing:
- `"prompt_input_ids"`: Concatenated prompt input IDs of shape `(2 * batch_size, prompt_length)`.
- `"completion_input_ids"`: Concatenated chosen and rejected completion input IDs of shape `(2 *
batch_size, max_completion_length)`.
- `"prompt_attention_mask"`: Concatenated prompt attention masks of shape `(2 * batch_size,
prompt_length)`.
- `"completion_attention_mask"`: Concatenated chosen and rejected attention masks of shape `(2 *
batch_size, max_completion_length)`.
- `"pixel_values"` (optional): Concatenated pixel values if `"prompt_pixel_values"` are present.
- `"pixel_attention_mask"` (optional): Concatenated pixel attention masks if
`"prompt_pixel_attention_mask"` are present.
Notes:
The completion input IDs and attention masks are padded to the maximum completion length of the chosen or
rejected sequences.
rr_Úprompt_attention_maskrér`)Ú pad_valueÚcompletion_input_idsÚchosen_attention_maskÚrejected_attention_maskÚcompletion_attention_mask)rLrrGrcrB)rr+r.rvrvrwÚconcatenated_inputsÕs2+
ÿ
ÿþÿþÿz&_UnslothDPOTrainer.concatenated_inputsrirrr™Ú model_outputc"C|jj}| |¡|j | |¡}| |¡|j | |¡} |jtjjkrLtj }
|j
r;tj |j
vr;t |j
tj ƒ}
t
| |
ƒt
||
ƒ|
} n<||} |jr_tjdg| j| jd}
n||}
|  |jj¡} |
 |jj¡}
| |
} |jtjjkrˆ| t |¡t | ¡8} |dkr¨t |j| ¡ d|jt |j | ¡|j}n/|dkrÏt |j| ¡ d|jt |j | ¡|jdd|j}n|dkrddl}|jdkràd |_|j|  ¡t |j| ¡| d|j¡|j |  ¡t |j | ¡| |j¡}nÇ|d
kr!t d|j| ¡}n¶|d kr3| dd|jd}n¤|d krx||}||} |j|}|j| }t ||fd¡ ¡ ¡}|j |¡|jj}t |j||¡ t |j| | ¡}n_|d
kr™||}||}|d|jd|d|jd}n>|dkrÄ|||j}|||j}t |¡ dt | ¡dt | ¡}n|dkr||}||} tj |dd\}}tj | dd\}}||}t |j|¡ d|jt |j |¡|j}nÕ|dkr@||} ||}
tj | dd\}}tj |
dd\}}||}t |j|¡ d|jt |j |¡|j}n—|dkr\dt |j|¡}t |j| ¡}||}n{|dkrzt |j|¡}dt |j|| ¡}||}n]|dkr°||} ||}
| |
} | |j} t | |j!j"¡}t | ¡ }t #| ¡}|d|||}n'|dkrÎ|d} |j$d}!|  %|!¡}t &|¡}t &|¡}n t'd|j(dƒ|j| |¡| |¡ ¡}|j| |¡| |¡ ¡}|||fS)a
Compute the DPO loss for a batch of policy and reference model log probabilities.
Args:
chosen_logps (`torch.FloatTensor`):
Log probabilities of the model for the chosen responses. Shape: `(batch_size,)`.
rejected_logps (`torch.FloatTensor`):
Log probabilities of the model for the rejected responses. Shape: `(batch_size,)`.
ref_chosen_logps (`torch.FloatTensor`):
Log probabilities of the reference model for the chosen responses. Shape: `(batch_size,)`.
ref_rejected_logps (`torch.FloatTensor`):
Log probabilities of the reference model for the rejected responses. Shape: `(batch_size,)`.
Returns:
A tuple of three tensors: `(losses, chosen_rewards, rejected_rewards)`. The losses tensor contains the DPO
loss for each example in the batch. The `chosen_rewards` and `rejected_rewards` tensors contain the rewards
for the chosen and rejected responses, respectively.
r)rrir`ÚrobustrÚexo_pairNgü©ñÒMbP?rqrrrsrtgà?ruÚaot_pairr_ÚaotrvrwÚdiscopopÚsftÚnll_losszUnknown loss type: z§. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', 'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_pair', 'discopop', 'apo_zero', 'apo_down', 'sft']))r…rrer9rÚALPHA_DIVERGENCEÚvaluerÚALPHA_DIVERGENCE_COEF_DEFAULTr§rr)rLÚtensorr¼Ú
JS_DIVERGENCErÚsoftplusÚ
logsigmoidr7r:ÚmathriÚlogÚrelurÚmeanÚdetachr´ÚupdateÚsortrZr>ÚexprcÚexpandÚ
zeros_likerr™)"rJrrr™r%rÚchosen_logratiosÚrejected_logratiosÚ
alpha_coefrmÚ logratiosÚ
ref_logratiosÚlossesr4Úchosen_rewardsÚrejected_rewardsÚrewardsÚdeltaÚchosen_logratios_sortedÚrejected_logratios_sortedÚlogratios_sortedÚref_logratios_sortedÚ
losses_chosenÚlosses_rejectedÚlog_ratio_modulationÚlogistic_componentÚ
exp_componentÚsft_lossrôrvrvrwÚdpo_loss""ÿÿÿ ý

 ÿ,þ




 
ÿ
(

ÿþÿ
ÿÿ
ÿÿ





  



  ÿ
z_UnslothDPOTrainer.dpo_lossc) CsR|j |¡}|j||jd}i}|jrd|d<d|vr!|d|d<d|vr+|d|d<d|vr5|d|d<|d}|d}|jrÜ| ¡|d |ddd
}t|d |jj ƒ} | 
¡| |d|j |dd d
}
|
j } d} |j s|j
dur|j |j
¡}
|
 ¡|d |ddd
}|
 
¡| |d|j |dd d
}|j } n7|j sÒ| ¡(| ¡|d |ddd
}| 
¡| |d|j |dd d
}|j } Wdƒn1sÍwY|d }| ¡}n¼tj|d |d fdd}tj|d|dfdd}tjt |¡|fdd}|jdurˆ|j| d¡krˆ|jdkrBt|||ƒ\}}}|ddd|jf}|ddd|jf}|ddd|jf}nO|jdkrt|||ƒ\}}}|dd|j df}|dd|j df}|dd|j df}t|||ƒ\}}}ntd|jdƒt|||ƒ\}}}|jr®|jddd ¡}|jd| ¡d}||d<d|d<|jrÛ|| ¡ d¡}|| ¡ d¡}|  d¡| ¡ d¡d}||d<n||d<t!|dƒrê| 
¡}nt"||j#j$|ƒ}||fdd i|¤Ž}|j ddddf} d} |j sC|j
durC|j |j
¡}
t!|
dƒr%|
 
¡}nt"|
|j#j$|
ƒ}||fdd i|¤Ž}|j ddddf} nA|j s„t!|dƒrR| 
¡}nt"||j#j$|ƒ}| ¡||fdd i|¤Ž}|j ddddf} Wdƒn 1swYt %|dk||j&¡}|ddddf}| }d}d}|j sÝ|j
dur¶|j |j
¡}
|
 }n| ¡ | }Wdƒn 1sÊwY|j(}t!|dƒrÛ|j)nd}|j*|j(| |t!|dƒrì|j)nd|j só| nd|j sú|nd|j s|ndd} | \}!^}"}#}$}%}&}'|!|"|#|$|%|&|'d|'ddœ}(|jr'|j+|(d <|(S)!N©r+Trorr#)Úattention_maskÚ return_dictr F)rWÚencoder_hidden_statesÚencoder_attention_maskÚ use_cacher`r_Ú
keep_startrúUnknown truncation mode: 'ú/'. Should be one of ['keep_end', 'keep_start'].©Úas_tupleÚlogits_to_keepÚoutput_hidden_statesrÚ position_idsrWÚ get_decoderr[rZÚbias)reÚ ref_inputÚ
ref_weightÚref_bias)ÚlossrrÚmean_chosen_logitsÚmean_rejected_logitsr,rDrEÚaux_loss),r…rr$r+r“Ú get_encoderrJÚdecoder_start_token_idrdÚlast_hidden_stater9rYrÚboolrLrr=r/Úsizer0r0r1rr)ÚnonzeroÚminrcÚitemr1rhÚcumsumrŽr rZr6Úwherer,Úget_output_embeddingsÚweightrerrl))rJrÚunwrapped_modelÚconcatenated_batchÚ model_kwargsrr#Úencoder_outputsÚdecoder_input_idsÚdecoder_outputsÚ
hidden_statesÚref_hidden_statesÚunwrapped_ref_modelÚref_encoder_outputsÚref_decoder_outputsÚlabelsÚ loss_maskrárWÚfirst_compute_indexrarcÚ
base_modelÚoutputsÚref_base_modelÚ ref_outputsÚmasked_input_idsÚlm_headrgrhÚ ref_lm_headÚ loss_outputrirrÚchosen_logits_meanÚrejected_logits_meanr,Ú aux_outputsrËrvrvrwÚ_compute_loss_ligerêsn    ýþûýû
ýûó ÿþ þ   ÿ
 
ÿþý 

ÿÿþý 

ÿþýú 


ÿù ýø
z&_UnslothDPOTrainer._compute_loss_ligerrc/Cs|djd}|j||jd}ddi}|jrd|d<d|vr$|d|d<d |vr.|d |d <d
|vr8|d
|d
<|d}|d }|d } |d
}
|jrh| } |j| |
dk<|d,||| dœ|¤Ž} | j}
|
 ¡}n1tj || fdd}tj ||
fdd}tj t 
|¡|
fdd}|j dur |j |  d¡kr |j
dkrÅt|||ƒ\}}}|ddd|j f}|ddd|j f}|ddd|j f}nO|j
dkrt|||ƒ\}}}|dd|j df}|dd|j df}|dd|j df}t|||ƒ\}}}ntd|j
dƒt|||ƒ\}}}|jr1|jddd ¡}|jd| ¡d}||d<d|d<|jr^|| ¡ d¡}|| ¡ d¡}| d¡| ¡ d¡d}||d<n||d<||fi|¤Ž} | j}
tj|ddd} tj|ddd ¡}|jr™| dd| df} |dd| df}|
jdd| jddkr¸| jd}|
dd| df}
d| |<t|
| ƒ}d||<tj|ddd}|jrí|j\}}tj||| jj| jjd}||| ¡<|}|ddddf d¡}i}|jrOt ¡Bt j!|
dd}tj"d|dd}||}|| d¡| d¡}|d|}||d}tj#t $||¡dd|d <Wdƒn 1sJwY|j%j&dus\d!|j'vr˜|jsj|
d|ddfn|
d|} |js~| d|ddfn| d|}!t j(tj)| dd"tj)|!dd"dd#|d$<d%|j'vr¥|| d¡}|j%j*dur|s|jdd}"|"d|}#|"|d}$t |#|$¡}%tj |%|%gdd}%|  d¡}tj+||jd& ,|¡}||% d¡k}&||" d¡k}'|&|'@ }(|&|'@ })||(jdd}*||)jdd}+|*|j%j*|+}|d||d'<||d|d(<|jrX|dkjddd|},|
dd|,…f|dd|,…f }-|
d|,df|d|,df }.n|
d||d| }-|
|d||d }.|-|d)<|.|d*<|jr…| j/|d+<|S)-a
Runs the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
We do this to avoid doing two forward passes, because it's faster for FSDP.
Args:
model:
Model to run the forward pass on.
batch:
Batch of input data.
is_ref_model:
Whether this method is being called for the reference model. If `True`, length desensitization is not
applied.
rrVr[FTrorr r#)rWr„r`r_Nr\rr]r^r_rarbrcrWrZ)ÚshiftsÚdimsr)r)rGÚpolicy_weightsr+)Úend_dim)rjr,rr©rrrrjrkrlrv)0rcr$r+r“r,rmrprLrr=r/rqr0r0r1rr)rrrsrtr1rhruÚrollrIÚzerosrÚsumr;rrÚ log_softmaxrjÚclampr;rZr<r™Ú
cross_entropyÚflattenr=ÚarangeÚ expand_asrr7rl)/rJrrÚ num_examplesrzr{rr r#r„rˆrmr…rWr†rarcÚseq_lenruÚper_token_logps_Ú all_logpsrËÚlogprobsÚweights_adjustment_factorÚper_token_logps_adjustedÚ all_weightsÚchosen_weightsÚrejected_weightsÚ
chosen_logitsÚ
chosen_labelsÚcompletion_lengthsÚchosen_lengthsÚrejected_lengthsÚpublic_lengthsÚld_maskÚmaskÚ
front_maskÚ rear_maskÚ front_logpsÚ
rear_logpsÚ split_idxrjrkrvrvrwrÑs   ýü  þ
  ÿ





ÿ 
  ø
((
ÿ     
 $&
z'_UnslothDPOTrainer.concatenated_forwardr|Ú
train_eval)r|c Ci}|jjr| ||¡}|d}|d}|d}n[| ||¡}d|vr0d|vr0|d} |d}
n| |¡\} }
d}d}d}t|jƒD]1\} } | |d|d| |
| |¡\}
}}|jr_|j| nd }||
|}|||}|||}qB||k  ¡}|jj
d
urŠ||jj
|d }|j r“||d }|j rŸ||j
|d
}|dkr¥dnd}|j |¡ ¡ ¡||d<|j |¡ ¡ ¡||d<|j |¡ ¡ ¡||d<|j ||¡ ¡ ¡||d<|j |d¡ ¡ ¡ ¡||d<|j |d¡ ¡ ¡ ¡||d<|j |d¡ ¡ ¡ ¡||d<|j |d¡ ¡ ¡ ¡||d<|jj
d
us>d|jvrQ|j |d ¡ ¡ ¡ ¡||d <|j rh|j |d
¡ ¡ ¡ ¡||d
<| ¡|fS)zWCompute the DPO loss and other metrics for the given batch of inputs for train or test.rirDrErrrrˆNr,r•rlÚeval_r“zrewards/chosenzrewards/rejectedzrewards/accuracieszrewards/marginsz logps/chosenzlogps/rejectedrjz
logits/chosenrkzlogits/rejectedr+)rZr5rrrÿÚ enumerater™rUr?rr<r;r…rr7rtr8)rJrr¸Úmetricsr%rCrDrEÚidxr™Ú_lossesÚ_chosen_rewardsÚ_rejected_rewardsrxÚreward_accuraciesÚprefixrvrvrwÚget_batch_loss_metrics®sn 
 

ú
     ÿ ÿ ÿ ÿ ÿ ÿ ÿ z)_UnslothDPOTrainer.get_batch_loss_metricsÚinputscCs~|jr
t|jjjƒntƒ}||j||dd\}}Wdƒn1s$wY| |jj¡}|j |dd|r=||fS|S)Nr|©r¸)
r(r…rrr?rerZÚ
store_metrics)rJÚreturn_outputsÚnum_items_in_batchÚcompute_loss_context_managerrirvrvrwÚ compute_losssÿÿz_UnslothDPOTrainer.compute_lossc Cs0|jr
t|jjjƒntƒ}|]|j|d|d|jd|jd}d|vr)|d}n<|j durT| 
¡|j j|d|d|jd|jd}Wdƒn1sNwYn|j j|d|d|jd|jd}Wdƒn1sowYt ||j|jƒ}|j
j|dd}t ||j|jƒ}|j
j|dd}||fS)zRGenerate samples from the model and reference model for the given batch of inputs.rârT)rWr/Ú do_samplerfÚ
ref_outputN)Úskip_special_tokens)r(r…rrr?Úgenerater/r+rYrrBr^Ú batch_decode)rJrÚgenerate_context_managerÚ
policy_outputrËÚpolicy_output_decodedÚref_output_decodedrvrvrwÚgenerate_from_model_and_refsJÿû


ûÿ ûéz._UnslothDPOTrainer.generate_from_model_and_refr©Ú ignore_keysc s ˆdurt|dƒrt|jdgƒng|jrt|jjjƒntƒ}t  
¡$||j ||dd\}}Wdƒn1s<wYWdƒn1sKwY|j |dd|r`| 
¡ddfS|d|ddœ}fdd „| ¡Dƒ} t j| |jjd
} t j| jd |jjd
}
| 
¡| |
fS) NrŠÚkeys_to_ignore_at_inferencerƒúeval_logits/chosenúeval_logits/rejected)r×csg|]
\}}|ˆvr|qSrvrv)r~ÚrvrwÚ
<listcomp>lsz6_UnslothDPOTrainer.prediction_step.<locals>.<listcomp>r—r)r r(r…rrr?rLrr8r0r™rc) rJÚprediction_context_managerriÚ logits_dictrmr„rvrwÚprediction_stepMs*
ÿÿþz"_UnslothDPOTrainer.prediction_stepr»cCs*| ¡D]\}}|j|| |¡qdSry)rk)rJr¸rr.rvrvrwrsÿz _UnslothDPOTrainer.store_metricsrƒÚ
dataloaderÚ descriptionÚmetric_key_prefixc|jrrt|jƒ}tjt|ƒ|jjd}|j |¡}|  |¡} | 
| ¡} |  |j | ¡\}
} t
jgd¢ddt|d|
| ƒDƒd} d|jjvrU|jjrUt dtj| d i¡d
|jjvratd | d d
|jjvrr|jjrrtj| ddtƒ |||||¡}
|
S)
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by