Skip to main content
TRL is designed with modularity in mind so that users can efficiently customize the training loop for their needs. The techniques below apply to most (if not all) trainers in TRL.
The examples on this page use [DPOTrainer], but the same customization patterns apply across all TRL trainers.

Custom optimizers and schedulers

By default, TRL trainers create a torch.optim.AdamW optimizer. You can pass a custom optimizer directly:

Adding a learning rate scheduler

Pass both optimizer and scheduler as a tuple via optimizers:

8-bit reference models

TRL supports all keyword arguments accepted by from_pretrained, including load_in_8bit via BitsAndBytesConfig for more memory-efficient fine-tuning:
See the Transformers PEFT docs for more on 8-bit and 4-bit model loading.

Custom callbacks

Callbacks let you execute code at specific points during training — useful for custom logging, monitoring, or early stopping.
Callbacks inherit from transformers.TrainerCallback. You can override any lifecycle hook such as on_train_begin, on_epoch_end, on_evaluate, and more.

Custom evaluation metrics

Define a compute_metrics function and pass it to the trainer. The function receives an EvalPrediction object containing logits and labels:

Mixed precision training

Mixed precision can significantly speed up training and reduce memory usage. Set bf16=True or fp16=True in the training config:
Use bf16=True on Ampere (A100, RTX 30xx) or newer GPUs. Use fp16=True on older architectures.

Gradient accumulation

Gradient accumulation simulates larger batch sizes on limited GPU memory by accumulating gradients over multiple steps before updating weights:
The effective batch size is: