5.1: FINE-TUNING WITH TRAINER & SEQ2SEQTRAINER — LOOPS, METRICS & CHECKPOINTS

Fine-tune transformer models cleanly using Trainer, TrainingArguments, Seq2SeqTrainer, data collators, evaluation metrics, and checkpoint management—with real-time examples and Python code.

🏋️ Summary: Standardized Fine-Tuning Without Rewriting Training Loops

Writing a raw PyTorch training loop from scratch for every fine-tuning experiment repeats hundreds of lines of boilerplate: gradient accumulation, learning-rate scheduling, mixed precision, evaluation passes, logging, and checkpoint saving. Hugging Face's Trainer (and Seq2SeqTrainer for sequence-to-sequence tasks like summarization or translation) encapsulates that training orchestration cleanly around your model, TrainingArguments, tokenized datasets, data collator, and compute_metrics function.

When using Trainer, aligning eval_strategy, save_strategy, and load_best_model_at_end ensures you keep the best validation checkpoint rather than blindly taking the final epoch, while callbacks and data collators handle real-world details like dynamic batch padding and early stopping.

1. Trainer, TrainingArguments & Seq2SeqTrainer Core Pieces
Key building blocks that make Trainer and Seq2SeqTrainer reliable across tasks:
  • TrainingArguments & Seq2SeqTrainingArguments: Centralize hyperparameters and runtime settings—output_dir, learning rate, batch size, gradient_accumulation_steps, eval_strategy, save_strategy, load_best_model_at_end, and mixed precision (fp16 / bf16). Seq2SeqTrainingArguments adds sequence-generation options like predict_with_generate=True.
  • Data Collators & Tokenizers: Data collators (such as DataCollatorWithPadding or DataCollatorForSeq2Seq) dynamically pad batches and format labels cleanly during training.
  • compute_metrics & Checkpoints: Passing a compute_metrics callback reports task metrics (like F1 or accuracy) during evaluation, while checkpoints in output_dir let you resume interrupted runs or reload the best model.
Class / Concept Primary Role Practical Watchout
Trainer Standard training & eval loop for encoders/causal LMs Ensure label column is named labels
Seq2SeqTrainer Encoder-decoder / generative seq2seq fine-tuning Enable predict_with_generate for text metrics
load_best_model_at_end Reloads top validation checkpoint at finish Keep save_strategy aligned with eval_strategy
Python (trainer_classification_setup.py)
from datasets import Dataset
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    Trainer,
    TrainingArguments,
)

model_id = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=2)

train_raw = Dataset.from_dict({
    "text": [
        "Fast checkout and helpful support team.",
        "App crashes whenever I export my report.",
        "Smooth setup and clear documentation.",
        "Payment failed twice with no error message.",
    ],
    "label": [1, 0, 1, 0],
})
val_raw = Dataset.from_dict({
    "text": ["Works great on mobile.", "Login loop on password reset."],
    "label": [1, 0],
})

def tokenize_fn(batch):
    return tokenizer(batch["text"], truncation=True, max_length=128)

train_ds = train_raw.map(tokenize_fn, batched=True).rename_column("label", "labels")
val_ds = val_raw.map(tokenize_fn, batched=True).rename_column("label", "labels")

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    preds = logits.argmax(axis=-1)
    acc = float((preds == labels).mean())
    return {"accuracy": round(acc, 4)}

args = TrainingArguments(
    output_dir="./runs/ticket-classifier",
    eval_strategy="epoch",
    save_strategy="epoch",
    save_total_limit=2,
    load_best_model_at_end=True,
    metric_for_best_model="accuracy",
    per_device_train_batch_size=4,
    per_device_eval_batch_size=4,
    num_train_epochs=2,
    learning_rate=3e-5,
    logging_steps=1,
    report_to="none",
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=train_ds,
    eval_dataset=val_ds,
    processing_class=tokenizer,
    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),
    compute_metrics=compute_metrics,
)

# Uncomment to run training:
# trainer.train()
print("Trainer configured successfully | Eval rows:", len(val_ds))
Output: Trainer configured successfully | Eval rows: 2
2. Real-Time Examples (Part 1: Student & Lab Workflows)
Five real-time scenarios students encounter when fine-tuning models with Trainer or Seq2SeqTrainer:
  • 1. Domain Adaptation on Coursework / Lab Text: A student fine-tunes a compact classifier on domain-specific support tickets, academic abstracts, or product reviews where generic pre-trained labels don't fit well.
  • 2. Preventing Overfitting with Best-Checkpoint Selection: Training for too many epochs can memorize small lab datasets—setting eval_strategy="epoch", save_strategy="epoch", and load_best_model_at_end=True keeps the strongest validation checkpoint.
  • 3. Simulating Larger Batches on Limited GPU Memory: When batch size 16 triggers an out-of-memory error, using per_device_train_batch_size=4 with gradient_accumulation_steps=4 approximates an effective batch of 16 while using less VRAM.
  • 4. Using Seq2SeqTrainer for Summarization or Translation Labs: Students working on encoder-decoder models use Seq2SeqTrainer and DataCollatorForSeq2Seq so target sequences and label padding are handled properly.
  • 5. Resuming After a Notebook or Session Disconnect: Passing resume_from_checkpoint=True (or a checkpoint folder path) lets training pick up from the last saved checkpoint rather than starting over.
Python (effective_batch_and_checkpoint_helper.py)
def compute_effective_batch_size(per_device_batch: int, grad_accum_steps: int, num_devices: int = 1) -> int:
    return per_device_batch * grad_accum_steps * max(1, num_devices)

def validate_best_checkpoint_args(eval_strategy: str, save_strategy: str, load_best: bool):
    if load_best and eval_strategy != save_strategy:
        return False, "When load_best_model_at_end=True, eval_strategy and save_strategy should match."
    return True, "Checkpoint & evaluation strategies are aligned."

print("3. Effective batch size:", compute_effective_batch_size(4, 4, num_devices=1))
print("2. Strategy check      :", validate_best_checkpoint_args("epoch", "epoch", True))
Output: 3. Effective batch size: 16 2. Strategy check : (True, 'Checkpoint & evaluation strategies are aligned.')
3. Real-Time Examples (Part 2: Team & Production Workflows)
How engineering teams structure fine-tuning runs for reliability, cost control, and handoff:
  • 6. Capping Disk Usage with save_total_limit: Long multi-epoch runs can fill disk space with checkpoints—setting save_total_limit=2 keeps only the most recent/best checkpoints instead of dozens of large folders.
  • 7. Early Stopping to Save GPU Hours: Attaching EarlyStoppingCallback halts training automatically when validation metrics stop improving, saving compute on expensive cloud GPUs.
  • 8. Custom Loss via Subclassing Trainer: For class-imbalanced datasets, subclassing Trainer and overriding compute_loss() lets you apply weighted cross-entropy without rewriting the whole loop.
  • 9. Reproducible Seeds Across Experiment Runs: Setting a fixed seed in TrainingArguments makes hyperparameter comparisons fair across runs.
  • 10. Saving Final Model & Tokenizer Together for Inference: Calling trainer.save_model(final_dir) writes the trained weights and tokenizer files cleanly so downstream inference or deployment scripts can reload them directly.
Python (custom_weighted_loss_trainer.py)
import torch
from torch import nn
from transformers import Trainer

class WeightedLossTrainer(Trainer):
    """Example custom Trainer applying class weights for imbalanced classification."""

    def __init__(self, *args, class_weights=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.class_weights = class_weights

    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        labels = inputs.get("labels")
        outputs = model(**inputs)
        logits = outputs.get("logits")
        if self.class_weights is not None and labels is not None:
            weight = torch.tensor(self.class_weights, device=logits.device, dtype=logits.dtype)
            loss_fct = nn.CrossEntropyLoss(weight=weight)
            loss = loss_fct(logits.view(-1, model.config.num_labels), labels.view(-1))
        else:
            loss = outputs.get("loss")
        return (loss, outputs) if return_outputs else loss

print("8. WeightedLossTrainer subclass ready for imbalanced labels.")
Output: 8. WeightedLossTrainer subclass ready for imbalanced labels.
4. Practical Checkpoints for Trainer Workflows
Keep these habits in mind whenever you fine-tune with Trainer or Seq2SeqTrainer:
  • Verify column names and label types early: Models expect labels as integer class IDs (for classification) or token IDs (for seq2seq).
  • Align evaluation, saving, and disk limits: Match eval_strategy and save_strategy when using load_best_model_at_end=True, and set save_total_limit to protect disk space.
  • Start with full or light baseline on a small slice: Test your data pipeline, metrics, and checkpoint saving on a small subset before launching a full training run.
Python (trainer_best_practices_checklist.py)
checklist = [
    "Validate dataset columns ('labels') and run a quick subset smoke test first.",
    "Match eval_strategy and save_strategy when enabling load_best_model_at_end.",
    "Use gradient_accumulation_steps and save_total_limit to manage VRAM and disk."
]

for item in checklist:
    print("*", item)
Output: * Validate dataset columns ('labels') and run a quick subset smoke test first. * Match eval_strategy and save_strategy when enabling load_best_model_at_end. * Use gradient_accumulation_steps and save_total_limit to manage VRAM and disk.