
    ha                         S SK JrJr  S SKJr  S SKJrJrJrJ	r	  S SK
Jr   " S S\5      r " S S5      r\ " S	 S
\5      5       rg)    )	dataclassfield)Enum)AnyCallableOptionalUnion)TrainingArgumentsc                        \ rS rSrSrSrSrSrg)FDivergenceType   
reverse_kljs_divergencealpha_divergence N)__name__
__module____qualname____firstlineno__
REVERSE_KLJS_DIVERGENCEALPHA_DIVERGENCE__static_attributes__r       P/home/james-whalen/.local/lib/python3.13/site-packages/trl/trainer/dpo_config.pyr   r      s    J#M)r   r   c                       \ rS rSrSrSrSrg)FDivergenceConstants   alpha_divergence_coef      ?r   N)r   r   r   r   ALPHA_DIVERGENCE_COEF_KEYALPHA_DIVERGENCE_COEF_DEFAULTr   r   r   r   r   r      s     7$'!r   r   c                   :  ^  \ rS rSr% Sr\R                  SS/-   r\" SSS0S9r\	\
S	'   \" S
SS0S9r\	\
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\   \
S'   \" SSS0S9r\\\\4      \
S'   \" SSS0S9r\\\\4      \
S'   \" SSS0S9r\\   \
S'   \" SSS0S9r\\   \
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\
S'   \" SSS 0S9r\\   \
S!'   \" SSS"0S9r\\   \
S#'   \" S$SS%0S9r\\
S&'   \" S'SS(0S9r\\   \
S)'   \" SSS*0S9r\\   \
S+'   \" S,SS-0S9r \\   \
S.'   \" S/S0S/S1/S2.S9r!\\
S3'   \" SSS40S9r"\\
S5'   \" SSS60S9r#\\
S7'   \" SSS80S9r$\\   \
S9'   \" SSS:0S9r%\\&\'\\(4         \
S;'   \" S< SS=0S>9r)\&\   \
S?'   \" SSS@0S9r*\\
SA'   \" SBSSC0S9r+\\
SD'   \" SESSF0S9r,\	\
SG'   \" \-R\                  SSH0S9r/\-\
SI'   \" SJSSK0S9r0\	\
SL'   \" SSSM0S9r1\\
SN'   \" SOSSP0S9r2\	\
SQ'   \" SSSR0S9r3\\
SS'   \" SSST0S9r4\\	   \
SU'   \" SSSV0S9r5\\	   \
SW'   \" SXSSY0S9r6\	\
SZ'   \" SSS[0S9r7\\&\	      \
S\'   \" SSS]0S9r8\\
S^'   \" S_SS`0S9r9\	\
Sa'   \" S'SSb0S9r:\\
Sc'   \" SSSd0S9r;\\
Se'   U 4Sf jr<Sgr=U =r>$ )h	DPOConfig!   u+  
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.
model_init_kwargsref_model_init_kwargsgư>helpz$The initial learning rate for AdamW.)defaultmetadatalearning_rate
   zLog every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.logging_stepsTzZIf True, use gradient checkpointing to save memory at the expense of slower backward pass.gradient_checkpointingNzWhether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if `fp16` is not set.bf16zKeyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `DPOTrainer` is provided as a string.zKeyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `ref_model` argument of the `DPOTrainer` is provided as a string.zNName of the train target PEFT adapter, when using LoRA with multiple adapters.model_adapter_namezKName of the reference PEFT adapter, when using LoRA with multiple adapters.ref_adapter_nameFz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`.force_use_ref_modelz<Whether to disable dropout in the model and reference model.disable_dropouta  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).use_logits_to_keepz6Number of processes to use for processing the dataset.dataset_num_proczLPadding value to use. If `None`, the padding value of the tokenizer is used.padding_valueiz Padding value to use for labels.label_pad_token_idi   zMaximum length of the prompt.max_prompt_lengthz!Maximum length of the completion.max_completion_lengthi   z:Maximum length of the full sequence (prompt + completion).
max_lengthkeep_endzsTruncation mode to use when the sequence exceeds `max_length`. Possible values are `'keep_end'` and `'keep_start'`.
keep_start)r(   choicestruncation_modeaM  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.padding_freea@  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_log_probsa  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.precompute_ref_batch_sizezList 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.toolsc                      S/$ )Nsigmoidr   r   r   r   <lambda>DPOConfig.<lambda>L  s    r   a  Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, `'nca_pair'`, `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_pair'`, `'discopop'`, `'apo_zero'`, `'apo_down'` and `'sft'`. Multiple loss types can be combined using comma separation (e.g., `['sigmoid', 'bco_pair', 'sft']` for MPO). The `loss_weights` parameter can be used to specify corresponding weights for each loss type.)default_factoryr*   	loss_typezWhether to use Liger loss.use_liger_lossmodelzName 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`.base_model_attribute_nameg?uv   Parameter controlling the deviation from the reference model. Higher β means less deviation from the reference model.betazfType of f-divergence regularization function to compute divergence between policy and reference model.f_divergence_typer    uO   α coefficient in the α-divergence u^-α regularization function for DPO loss.f_alpha_divergence_coefzWhether to ignore the provided reference model and implicitly use a reference model that assigns equal probability to all responses.reference_freeg        zvRobust DPO label smoothing parameter from the cDPO report and Robust DPO paper that should be between `0.0` and `0.5`.label_smoothingz4Whether to weight the loss as done in the WPO paper.use_weightingu   α parameter from the RPO paper (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`.	rpo_alphau#  α parameter from the LD-DPO paper, 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`.ld_alphag?u   τ/temperature parameter from the DiscoPOP paper, which controls the shape of log ratio modulated loss. The paper recommends the default value `discopop_tau=0.05`.discopop_tauzList of loss weights for multi-loss combinations. Used when combining multiple loss types. Example: `[0.8, 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss types.loss_weightszWhether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using the `ref_model_mixup_alpha` parameter.sync_ref_modelg333333?u-  α parameter from the TR-DPO 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_mixup_alphau   τ parameter from the TR-DPO 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`.ref_model_sync_stepsz~Whether to generate and log completions from both the model and the reference model to W&B, MLFLow or Comet during evaluation.generate_during_evalc                   > U R                   c  U R                  (       + OU R                   U l         [        U R                  S5      (       a-  [	        U R                  5      S:X  a  U R                  S   U l        U R
                  bv  [        U R                  [        5      (       a  U R                  OU R                  /n[	        U R
                  5      [	        U5      :w  a  [        SU R
                   SU S35      e[        TU ])  5         g )N__len__   r   zLength of loss_weights list (z#) must match number of loss types (z).)r/   fp16hasattrrH   lenrU   
isinstancelist
ValueErrorsuper__post_init__)self
loss_types	__class__s     r   rd   DPOConfig.__post_init__  s    '+yy'8Odii	 4>>9--#dnn2E2J!^^A.DN (+5dnnd+K+KRVR`R`QaJ4$$%Z8 3D4E4E3F G"|2'  	r   )r/   rH   )?r   r   r   r   __doc__r
   _VALID_DICT_FIELDSr   r+   float__annotations__r-   r.   boolr/   r   r&   dictstrr   r'   r0   r1   r2   r3   r4   r5   intr6   r7   r8   r9   r:   r>   r?   r@   rA   rB   ra   r	   r   rH   rI   rK   rL   r   r   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rd   r   __classcell__)rg   s   @r   r$   r$   !   s   Zx +==ATVm@nn !@AM5  ! D
M5  $)p
$D  ! !
D(4.  38 8
3xS#X/  7< ;
78DcN3  ).jk)  ',gh'hsm  !& 4
!  "XYOT   % `
   ',RS'hsm  $)hi$M8C=  $<=  (-9:(x}  ,1=>,8C=  !&VW!J  !""L1
OS   4
L$  &+ (
&d  05 j
0x}  49 O
4E8DtX~./0  !+ 8
	ItCy 	 !67ND  &+ *
&s   G
D%  */** 
*  &+kl&U  ! 2
ND  # *
OU   PQM4  "' 
"Ix  !& t
!Hhuo    P
L%  +0 
+L(4;'  ! B
ND  $) y
$5  !& q
!#  "' *
"$    r   r$   N)dataclassesr   r   enumr   typingr   r   r   r	   transformersr
   r   r   r$   r   r   r   <module>rv      sK    )  1 1 **d *( (
 q ! q  q r   