Ultralytics YOLO27: Join the waitlist.
License YOLO
Back to Ultralytics Glossary

Callback

A callback is a function a training loop calls at set events, such as each epoch's end, to add early stopping, checkpoints, or logging.

A callback is a function passed to another piece of code, which calls it back when a specific event happens. Event handlers in user interfaces, completion functions in asynchronous code, and the comparison function given to a sorting routine are all callbacks. In deep learning frameworks, the events are points in the training loop, such as the start of training, the end of each batch or epoch, and the moment validation finishes. Callbacks registered for an event run there with access to the trainer's state, so users can add early stopping against overfitting, checkpointing, learning rate schedules, or logging without editing the loop itself.

How Callbacks Hook into Training#

A framework keeps a list of callbacks for each named event and calls every one of them when the loop reaches that event, passing the trainer or model object so a callback can read metrics and change settings. Keras collects them in its keras.callbacks module, PyTorch Lightning in subclasses of Callback, and Hugging Face Transformers in TrainerCallback. Method names differ between libraries, and the events follow the same loop:

Because callbacks run inside the loop, they can also change it: a callback that sets a stop flag ends training after the current epoch, and one that edits the optimizer changes every step that follows. Callbacks for the same event run in the order they were registered, and batch-level callbacks run thousands of times per epoch, so slow work such as uploading files belongs in epoch-level events. In distributed training, every process runs its own copy of the loop and its callbacks, so logging and checkpointing callbacks usually act only on the main process, rank 0, to avoid writing the same file from several GPUs.

Common Training Callbacks#

  • Early stopping: Halts training when a validation metric has not improved for a set number of epochs, called the patience, which limits overfitting and saves compute. Keras's EarlyStopping can also restore the best weights it saw before stopping.
  • Checkpointing: Saves the model every epoch or whenever a monitored metric improves, so the best weights survive and a crashed run can resume. Keras's BackupAndRestore callback uses saved state to resume an interrupted run automatically.
  • Learning rate scheduling: Lowers the learning rate when a metric plateaus, as Keras's ReduceLROnPlateau does, or follows a fixed schedule such as cosine decay.
  • Experiment tracking: Sends losses, metrics, and sample images to tools such as TensorBoard, MLflow, or Weights & Biases after each epoch.
  • Hyperparameter tuning: Reports each epoch's score to a tuner such as Ray Tune, whose schedulers stop unpromising trials early.

Writing a Custom Callback#

Ultralytics YOLO fires named events during training, validation, prediction, and export, such as on_train_epoch_end and on_fit_epoch_end, and its own integrations for MLflow, Comet, ClearML, TensorBoard, and Ultralytics Platform are registered as callbacks on those events. This callback reads the validation mAP50-95 after each epoch and stops a YOLO26 run as soon as it reaches a target:

from ultralytics import YOLO


def stop_at_target(trainer):
    """Stop training once validation mAP50-95 reaches 0.6."""
    score = trainer.metrics["metrics/mAP50-95(B)"]
    print(f"Epoch {trainer.epoch + 1}: mAP50-95 {score:.3f}")
    if score >= 0.6:
        trainer.stop = True  # the trainer ends the run after this epoch


model = YOLO("yolo26n.pt")
model.add_callback("on_fit_epoch_end", stop_at_target)  # runs after each epoch's validation
model.train(data="coco8.yaml", epochs=20)

The on_fit_epoch_end event fires after training and validation for the epoch, so trainer.metrics already holds that epoch's scores. Setting trainer.stop makes the trainer leave its epoch loop, run its usual final validation of the best weights, and save the results, as it does when the built-in patience limit is reached.

Callbacks vs. Hooks#

The two words often name the same thing: PyTorch Lightning calls the methods a callback implements hooks. In PyTorch itself, module hooks registered with register_forward_hook or register_full_backward_hook attach to a single layer's forward or backward pass instead of a training-loop event, and they are used to read feature maps for visualization or to inspect and modify gradients during backpropagation.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning