Buckets:
KTO Trainer
As of TRL v1.0,
KTOTrainerandKTOConfighave been moved to thetrl.experimental.ktomodule.
KTO API is experimental and may change at any time. Promoting KTO back into the stable API is a high-priority task: KTO is slated for refactoring to align with the standard core trainer architecture.
Overview
Kahneman-Tversky Optimization (KTO) was introduced in KTO: Model Alignment as Prospect Theoretic Optimization by Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, Douwe Kiela.
The abstract from the paper is the following:
Kahneman & Tversky's prospect theory tells us that humans perceive random variables in a biased but well-defined manner; for example, humans are famously loss-averse. We show that objectives for aligning LLMs with human feedback implicitly incorporate many of these biases -- the success of these objectives (e.g., DPO) over cross-entropy minimization can partly be ascribed to them being human-aware loss functions (HALOs). However, the utility functions these methods attribute to humans still differ from those in the prospect theory literature. Using a Kahneman-Tversky model of human utility, we propose a HALO that directly maximizes the utility of generations instead of maximizing the log-likelihood of preferences, as current methods do. We call this approach Kahneman-Tversky Optimization (KTO), and it matches or exceeds the performance of preference-based methods at scales from 1B to 30B. Crucially, KTO does not need preferences -- only a binary signal of whether an output is desirable or undesirable for a given input. This makes it far easier to use in the real world, where preference data is scarce and expensive.
The official code can be found in ContextualAI/HALOs.
This post-training method was contributed by Kashif Rasul, Younes Belkada, Lewis Tunstall and Pablo Vicente.
Quick start
This example demonstrates how to train a model using the KTO method. We use the Qwen 0.5B model as the base model. We use the preference data from the KTO Mix 14k. You can view the data in the dataset here:
Below is the script to train the model:
# train_kto.py
from datasets import load_dataset
from trl.experimental.kto import KTOConfig, KTOTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
train_dataset = load_dataset("trl-lib/kto-mix-14k", split="train")
training_args = KTOConfig(output_dir="Qwen2-0.5B-KTO")
trainer = KTOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset)
trainer.train()
Execute the script using the following command:
accelerate launch train_kto.py
Distributed across 8 x H100 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time.
To see how the trained model performs, you can use the Transformers Chat CLI.
$ transformers chat trl-lib/Qwen2-0.5B-KTO <quentin_gallouedec>: What is the best programming language?
<trl-lib/Qwen2-0.5B-KTO>: The best programming language can vary depending on individual preferences, industry-specific requirements, technical skills, and familiarity with the specific use case or task. Here are some widely-used programming languages that have been noted as popular and widely used:
Here are some other factors to consider when choosing a programming language for a project:
1 JavaScript: JavaScript is at the heart of the web and can be used for building web applications, APIs, and interactive front-end applications like frameworks like React and Angular. It's similar to C, C++, and F# in syntax structure and is accessible and easy to learn, making it a popular choice for beginners and professionals alike. 2 Java: Known for its object-oriented programming (OOP) and support for Java 8 and .NET, Java is used for developing enterprise-level software applications, high-performance games, as well as mobile apps, game development, and desktop applications. 3 C++: Known for its flexibility and scalability, C++ offers comprehensive object-oriented programming and is a popular choice for high-performance computing and other technical fields. It's a powerful platform for building real-world applications and games at scale. 4 Python: Developed by Guido van Rossum in 1991, Python is a high-level, interpreted, and dynamically typed language known for its simplicity, readability, and versatility.
Expected dataset format
KTO requires an unpaired preference dataset. Alternatively, you can provide a paired preference dataset (also known simply as a preference dataset). In this case, the trainer will automatically convert it to an unpaired format by separating the chosen and rejected responses, assigning label = True to the chosen completions and label = False to the rejected ones.
The experimental.kto.KTOTrainer supports both conversational and standard dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.
In theory, the dataset should contain at least one chosen and one rejected completion. However, some users have successfully run KTO using only chosen or only rejected data. If using only rejected data, it is advisable to adopt a conservative learning rate.
Example script
We provide an example script to train a model using the KTO method. The script is available in trl/scripts/kto.py
To test the KTO script with the Qwen2 0.5B model on the UltraFeedback dataset, run the following command:
accelerate launch trl/scripts/kto.py \
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
--dataset_name trl-lib/kto-mix-14k \
--num_train_epochs 1 \
--output_dir Qwen2-0.5B-KTO
Usage tips
For Mixture of Experts Models: Enabling the auxiliary loss
MOEs are the most efficient if the load is about equally distributed between experts.
To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.
This option is enabled by setting output_router_logits=True in the model config (e.g. MixtralConfig).
To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter router_aux_loss_coef=... (default: 0.001) in the model config.
Batch size recommendations
Use a per-step batch size that is at least 4, and an effective batch size between 16 and 128. Even if your effective batch size is large, if your per-step batch size is poor, then the KL estimate in KTO will be poor.
Learning rate recommendations
Each choice of beta has a maximum learning rate it can tolerate before learning performance degrades. For the default setting of beta = 0.1, the learning rate should typically not exceed 1e-6 for most models. As beta decreases, the learning rate should also be reduced accordingly. In general, we strongly recommend keeping the learning rate between 5e-7 and 5e-6. Even with small datasets, we advise against using a learning rate outside this range. Instead, opt for more epochs to achieve better results.
Imbalanced data
The desirable_weight and undesirable_weight of the experimental.kto.KTOConfig refer to the weights placed on the losses for desirable/positive and undesirable/negative examples.
By default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (desirable_weight number of positives) to (undesirable_weight number of negatives) is in the range 1:1 to 4:3.
Logged metrics
While training and evaluating, we record the following reward metrics:
rewards/chosen_sum: the sum of log probabilities of the policy model for the chosen responses scaled by betarewards/rejected_sum: the sum of log probabilities of the policy model for the rejected responses scaled by betalogps/chosen_sum: the sum of log probabilities of the chosen completionslogps/rejected_sum: the sum of log probabilities of the rejected completionslogits/chosen_sum: the sum of logits of the chosen completionslogits/rejected_sum: the sum of logits of the rejected completionscount/chosen: the count of chosen samples in a batchcount/rejected: the count of rejected samples in a batch
KTOTrainer[[trl.KTOTrainer]]
trl.KTOTrainer[[trl.KTOTrainer]]
Initialize KTOTrainer.
traintrl.KTOTrainer.trainhttps://github.com/huggingface/trl/blob/vr_5607/transformers/trainer.py#L1323[{"name": "resume_from_checkpoint", "val": ": str | bool | None = None"}, {"name": "trial", "val": ": optuna.Trial | dict[str, Any] | None = None"}, {"name": "ignore_keys_for_eval", "val": ": list[str] | None = None"}]- resume_from_checkpoint (str or bool, optional) --
If a str, local path to a saved checkpoint as saved by a previous instance of Trainer. If a
bool and equals True, load the last checkpoint in args.output_dir as saved by a previous instance
of Trainer. If present, training will resume from the model/optimizer/scheduler states loaded here.
- trial (
optuna.Trialordict[str, Any], optional) -- The trial run or the hyperparameter dictionary for hyperparameter search. - ignore_keys_for_eval (
list[str], optional) -- A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.0~trainer_utils.TrainOutputObject containing the global step count, training loss, and metrics.
Main training entry point.
Parameters:
model (str or PreTrainedModel or PeftModel) : 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 save_pretrained, e.g., './my_model_directory/'. The model is loaded using .from_pretrained (where `` is derived from the model config) with the keyword arguments in args.model_init_kwargs. - A PreTrainedModel object. Only causal language models are supported. - A PeftModel object. Only causal language models are supported.
ref_model (PreTrainedModel, optional) : Reference model used to compute the reference log probabilities. - If provided, this model is used directly as the reference policy. - If None, the trainer will automatically use the initial policy corresponding to model, i.e. the model state before KTO training starts.
args (experimental.kto.KTOConfig, optional) : Configuration for this trainer. If None, a default configuration is used.
train_dataset (Dataset) : The dataset to use for training.
eval_dataset (Dataset) : The dataset to use for evaluation.
processing_class (PreTrainedTokenizerBase or ProcessorMixin, optional) : 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 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.
data_collator (DataCollator, optional) : The data collator to use for training. If None is specified, the default data collator (experimental.utils.DPODataCollatorWithPadding) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
model_init (Callable[[], transformers.PreTrainedModel]) : The model initializer to use for training. If None is specified, the default model initializer will be used.
callbacks (list[transformers.TrainerCallback]) : The callbacks to use for training.
optimizers (tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]) : The optimizer and scheduler to use for training.
preprocess_logits_for_metrics (Callable[[torch.Tensor, torch.Tensor], torch.Tensor]) : The function to use to preprocess the logits before computing the metrics.
peft_config (dict, defaults to None) : The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
compute_metrics (Callable[[EvalPrediction], dict], optional) : The function to use to compute the metrics. Must take a EvalPrediction and return a dictionary string to metric values.
Returns:
~trainer_utils.TrainOutput
Object containing the global step count, training loss, and metrics.
save_model[[trl.KTOTrainer.save_model]]
Will save the model, so you can reload it using from_pretrained().
Will only save from the main process.
push_to_hub[[trl.KTOTrainer.push_to_hub]]
Upload self.model and self.processing_class to the 🤗 model hub on the repo self.args.hub_model_id.
Parameters:
commit_message (str, optional, defaults to "End of training") : Message to commit while pushing.
blocking (bool, optional, defaults to True) : Whether the function should return only when the git push has finished.
token (str, optional, defaults to None) : Token with write permission to overwrite Trainer's original args.
revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.
kwargs (dict[str, Any], optional) : Additional keyword arguments passed along to ~Trainer.create_model_card.
Returns:
The URL of the repository where the model was pushed if blocking=False, or a Future object tracking the
progress of the commit if blocking=True.
KTOConfig[[trl.KTOConfig]]
trl.KTOConfig[[trl.KTOConfig]]
Configuration class for the experimental.kto.KTOTrainer.
This class includes only the parameters that are specific to KTO training. For a full list of training arguments, please refer to the TrainingArguments documentation. Note that default values in this class may differ from those in TrainingArguments.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
These parameters have default values different from TrainingArguments:
logging_steps: Defaults to10instead of500.gradient_checkpointing: Defaults toTrueinstead ofFalse.bf16: Defaults toTrueiffp16is not set, instead ofFalse.learning_rate: Defaults to1e-6instead of5e-5.
Xet Storage Details
- Size:
- 18.1 kB
- Xet hash:
- bf34b62dcdc688158e4c0f798ac36f6d608af2e7966ca02feea1adce97029c76
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.
