opensi·si

Each recipe below demonstrates a specific Trainer feature: custom loss functions, memory-efficient evaluation, checkpointing strategies, and more.

Trainer features

Each recipe below demonstrates a specific Trainer feature: custom loss functions, memory-efficient evaluation, checkpointing strategies, and more.

Tip Open an issue if there is a feature or workflow you'd like to see here.

Custom loss function

Pass Trainer#compute_loss_func to Trainer to replace the default loss function. The function runs after the forward pass and only defines how loss is computed from the outputs. To modify the forward pass itself, subclass Trainer.compute_loss instead.

The custom loss function must have the following signature:

import torch.nn.functional as F

def my_loss_fn(outputs, labels, num_items_in_batch):
    logits = outputs["logits"]
    loss = F.cross_entropy(logits, labels, reduction="sum")
    return loss / num_items_in_batch
  • outputs is the raw model output (outputs.logits has shape (batch, seq_len, vocab_size)).
  • labels is the token ids popped from the input batch by Trainer before the forward pass.
  • num_items_in_batch is the number of prediction targets across the full accumulated batch. For causal LM models it counts the shifted labels (labels[..., 1:]), since the label shift leaves position 0 of every sequence without a target. See Loss scaling for details. Trainer skips automatic loss normalization when a custom loss function is provided, so your function must handle normalization directly.
trainer = Trainer(
    model=model,
    args=TrainingArguments(...),
    train_dataset=train_dataset,
    compute_loss_func=my_loss_fn,
)
trainer.train()

Note See the subclassing guide for more examples of overriding Trainer.compute_loss.

Evaluating on start

Set eval_on_start=True to run a full eval pass before the first training step. A pre-training eval surfaces issues with the evaluation pipeline early, especially during long runs.

eval_on_start requires a valid eval_strategy (such as "epoch") and an eval dataset.

from transformers import Trainer, TrainingArguments

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="out",
        eval_strategy="epoch",
        eval_on_start=True,
    ),
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    compute_metrics=compute_metrics,
)
trainer.train()

A full eval adds time, so it's most useful on first runs or after modifying compute_metrics.

Memory-efficient evals

During evaluation, Trainer runs a forward pass on every batch and concatenates the logits into a single tensor on the GPU. Once the eval dataset is fully processed, Trainer moves the concatenated logits to the CPU and calls compute_metrics. For large models or eval sets, the accumulated logits can exhaust GPU memory even when training on the same hardware works fine, because training only holds one batch of activations at a time.

eval_accumulation_steps

Offload the accumulated predictions from GPU to CPU every n batches. Lower values reduce GPU memory at the cost of more frequent CPU transfers.

from transformers import Trainer, TrainingArguments

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="out",
        eval_strategy="epoch",
        eval_accumulation_steps=16,   # move predictions to CPU every 16 batches
    ),
    eval_dataset=eval_dataset,
    compute_metrics=compute_metrics,
)
trainer.train()

preprocess_logits_for_metrics

Called once per eval batch on the GPU, immediately after the forward pass and before logit accumulation. The returned value replaces the logits in eval_pred.predictions. Running the computation at the batch level reduces per-batch tensor size and gives eval_accumulation_steps a smaller tensor to offload.

import evaluate
from transformers import Trainer, TrainingArguments

metric = evaluate.load("accuracy")

def preprocess_logits_for_metrics(logits, labels):
    if isinstance(logits, tuple):
        logits = logits[0]
    return logits.argmax(dim=-1)

def compute_metrics(eval_preds):
    preds, labels = eval_preds
    labels = labels[:, 1:].reshape(-1)
    preds = preds[:, :-1].reshape(-1)
    return metric.compute(predictions=preds, references=labels)

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="out",
        eval_strategy="epoch",
        eval_accumulation_steps=16,
    ),
    eval_dataset=eval_dataset,
    compute_metrics=compute_metrics,
    preprocess_logits_for_metrics=preprocess_logits_for_metrics,
)
trainer.train()

Dataloader performance

By default, Trainer creates a dataloader with dataloader_num_workers=0. Data is loaded in the main process while the GPU idles, which shows up as low GPU utilization between batches.

Both dataloader_persistent_workers and dataloader_prefetch_factor require dataloader_num_workers > 0.

  • dataloader_persistent_workers keeps worker subprocesses alive between epochs to avoid reinitializing from scratch, at the cost of higher memory.
  • dataloader_prefetch_factor controls how many batches each worker prepares in advance. With dataloader_prefetch_factor=2 and num_workers=4, up to 8 batches sit in memory while the GPU trains on the current one.
from transformers import TrainingArguments

args = TrainingArguments(
    output_dir="out",
    dataloader_num_workers=4,            # spawn 4 worker subprocesses
    dataloader_persistent_workers=True,  # keep them alive between epochs
    dataloader_prefetch_factor=2,        # each worker preloads 2 batches ahead
)

Group samples by length

Use train_sampling_strategy="group_by_length" to batch examples with similar lengths and reduce padding. When you don't provide precomputed lengths, Trainer infers them from the first model input in each dataset item. This also works when processor-based multimodal datasets return BatchFeature objects, because they are mapping-like feature containers.

from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="qwen3-vl-finetuned",
    train_sampling_strategy="group_by_length",
)

If a datasets.Dataset already has a precomputed length column, Trainer uses that column instead. The default column name is length. Set length_column_name when your dataset uses another name. This strategy requires a dataset with a known length and is ignored for datasets.IterableDataset.

Batch rebalance sampling

On variable-length datasets, imbalance within a micro-batch and across devices causes devices to waste time on padding and to idle at gradient synchronization steps.

Set train_sampling_strategy="batch_rebalance" in TrainingArguments to reduce both effects. For each optimizer step, the sampler:

  1. Sorts the batch's samples by length.
  2. Shards the sorted batch across devices so that the padded-token cost of each micro-batch is balanced. Micro-batches with long samples get fewer samples, and micro-batches with short samples get more.

This reduces padding within each micro-batch, and each device finishes a micro-batch at roughly the same time, which reduces idle time at synchronization and keeps peak memory lower than "group_by_length". This strategy is only supported for data-parallel training for now (tensor parallelism is not yet supported).

from transformers import Trainer, TrainingArguments

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="out",
        train_sampling_strategy="batch_rebalance",  # balance padding cost across devices
        per_device_train_batch_size=8,              # average samples per micro-batch
        length_column_name="length",                # optional: dataset column with precomputed lengths
    ),
    train_dataset=train_dataset,
)
trainer.train()

per_device_train_batch_size is an average here rather than an exact per-step count: some micro-batches have fewer samples and some have more, but the total number of samples trained per step stays the same as with a normal distributed sampling strategy.

The sampler needs the length of every sample to sort and balance batches. By default, the Trainer scans the full dataset once at the start of training to compute these lengths. To skip this scan, precompute the lengths into a dataset column (during preprocessing, for example) and pass its name as length_column_name ("length" by default).

NEFTune

NEFTune adds random noise to token embeddings during the forward pass. The noise acts as regularization and can improve performance for instruction fine-tuning.

Enable NEFTune by setting neftune_noise_alpha in TrainingArguments. Typical alpha values range from 5 to 15.

from transformers import Trainer, TrainingArguments

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="out",
        num_train_epochs=3,
        neftune_noise_alpha=5,
    ),
    train_dataset=train_dataset,
)
trainer.train()

NEFTune only affects training, and the original embedding layer is restored after training.