コールバック
Ultralyticsフレームワークはコールバックをサポートしており、train、val、predict、exportの各モードにおける主要な段階でエントリーポイントとして機能します。操作の種類に応じて、各コールバックはTrainer、Validator、Predictor、またはExporterオブジェクトを受け取ります。
視聴: Ultralytics コールバックの使い方 | Predict、Train、Validate、Export のコールバック | Ultralytics YOLO26 🚀
例#
予測時に追加情報を返す#
この例では、各結果オブジェクトとともに元のフレームを返します:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Combine prediction results with corresponding frames."""
_, image, _ = predictor.batch
# image がリストであることを確認します
image = image if isinstance(image, list) else [image]
# 予測結果を対応するフレームと結合します
predictor.results = zip(predictor.results, image)
# YOLO モデルのインスタンスを作成します
model = YOLO("yolo26n.pt")
# カスタムコールバックをモデルに追加します
model.add_callback("on_predict_batch_end", on_predict_batch_end)
# 結果とフレームを順に処理します
for result, frame in model.predict(): # または model.track()
passトレーニング前に PyTorch の Forward Hook を登録する#
model.train() はモデル設定からトレーニングモデルを構築し、読み込んだ重みをそのモデルに転送します。この呼び出しより前に model.model に直接登録した PyTorch フックはランタイム状態であるため、再構築されたトレーニングモデルには引き継がれません。モデルのセットアップ完了後、on_pretrain_routine_end でトレーニング用フックを登録してください。
from ultralytics import YOLO
from ultralytics.utils.torch_utils import unwrap_model
def preprocess_input(module, inputs):
"""Center each input channel before the first model layer."""
images = inputs[0]
return (images - images.mean(dim=(-2, -1), keepdim=True),)
def register_forward_pre_hook(trainer):
"""Attach preprocessing to the active training model."""
train_model = unwrap_model(trainer.model)
train_model.model[0].register_forward_pre_hook(preprocess_input)
model = YOLO("yolo26n.pt")
model.add_callback("on_pretrain_routine_end", register_forward_pre_hook)
model.train(data="coco8.yaml", epochs=1)unwrap_model() は、単一デバイスと DistributedDataParallel の両方のトレーニングを処理します。トレーニングチェックポイントでは EMA モデルがシリアライズされ、チェックポイントの読み込み時に別のプロセスがコールバックをインポートできない可能性があるため、ローカルで定義したフックを trainer.ema.ema にアタッチしないでください。トレーニング中の検証でも同じ前処理を実行する必要がある場合は、ランタイムフックではなく、インポート可能なモデルコンポーネントとして実装してください。この方法で登録したフックは、NaN の復旧時に EMA がトレーニングモデルから再構築されるため、復旧後の EMA と保存済みチェックポイントにコピーされます。チェックポイントを別のプロセスで読み込む必要がある場合は、インポート可能なモジュール内でフック関数を定義してください。
スタンドアロンの model.val() は、呼び出しごとに読み込んだモデルをコピーします。予測では初回呼び出し時にコピーを作成してキャッシュするため、最初の model.predict() または model.track() の呼び出しより前に、model.model にフックを登録してください。後から追加したフックは、キャッシュ済みの予測器には反映されません。新しいプロセスでチェックポイントを読み込んだ後は、ランタイムフックを再度登録してください。
on_model_save コールバックを使用したモデルメトリクスへのアクセス#
この例では、on_model_save コールバックを使用してチェックポイントを保存した後、best_fitness スコアや total_loss などのトレーニングの詳細と、その他のメトリクスを取得する方法を示します。
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo26n.pt")
def print_checkpoint_metrics(trainer):
"""Print trainer metrics and loss details after each checkpoint is saved."""
print(
f"Model details\n"
f"Best fitness: {trainer.best_fitness}, "
f"Loss names: {trainer.loss_names}, " # List of loss names
f"Metrics: {trainer.metrics}, "
f"Total loss: {trainer.tloss}" # Total loss value
)
if __name__ == "__main__":
# Add on_model_save callback.
model.add_callback("on_model_save", print_checkpoint_metrics)
# Run model training on custom dataset.
results = model.train(data="coco8.yaml", epochs=3)すべてのコールバック#
以下に、サポートされているすべてのコールバックを示します。詳しくは、コールバックのソースコードを参照してください。
トレーナーのコールバック#
| コールバック | 説明 |
|---|---|
on_pretrain_routine_start | データ読み込みとモデルのセットアップを行う前に、事前トレーニングルーチンの開始時に呼び出されます。 |
on_pretrain_routine_end | データ読み込みとモデルのセットアップが完了した後、事前トレーニングルーチンの終了時に呼び出されます。 |
on_train_start | トレーニング開始時に、最初のエポックが始まる前に呼び出されます。 |
on_train_epoch_start | 各トレーニングエポックの開始時、バッチの反復処理が始まる前にトリガーされます。 |
on_train_batch_start | 各トレーニングバッチの開始時に、順伝播の前に呼び出されます。 |
optimizer_step | オプティマイザーステップ中に呼び出されます。カスタム連携用に予約されており、デフォルトのトレーニングループでは呼び出されません。 |
on_before_zero_grad | 勾配をゼロにする前に呼び出されます。カスタム連携用に予約されており、デフォルトのトレーニングループでは呼び出されません。 |
on_train_batch_end | 逆伝播後、各トレーニングバッチの終了時に呼び出されます。勾配蓄積により、オプティマイザーステップが延期される場合があります。 |
on_train_epoch_end | すべてのバッチの処理後、各トレーニングエポックの終了時に呼び出されますが、検証の前です。検証メトリクスと fitness はまだ利用できない場合があります。 |
on_model_save | 検証後、モデルのチェックポイントが保存されるときに呼び出されます。 |
on_fit_epoch_end | 検証とチェックポイントの保存後、各 fit エポック(train + val)の終了時に呼び出されます。検証メトリクスを利用でき、エポックごとのトレーニング呼び出しでは fitness も利用できます。このコールバックは最良モデルの最終評価中にも呼び出されますが、その際はチェックポイントの保存は行われず、fitness が存在しない場合があります。 |
on_train_end | 最良モデルの最終評価後、トレーニングプロセスの終了時に呼び出されます。 |
on_params_update | モデルパラメーターが更新されたときに呼び出されます。カスタム連携用に予約されており、デフォルトのトレーニングループでは呼び出されません。 |
teardown | トレーニングプロセスのクリーンアップ時に呼び出されます。 |
バリデーターのコールバック#
| コールバック | 説明 |
|---|---|
on_val_start | 検証開始時に呼び出されます。 |
on_val_batch_start | 各検証バッチの開始時に呼び出されます。 |
on_val_batch_end | 各検証バッチの終了時に呼び出されます。 |
on_val_end | 検証終了時に呼び出されます。 |
予測器のコールバック#
| コールバック | 説明 |
|---|---|
on_predict_start | 予測プロセスの開始時に呼び出されます。 |
on_predict_batch_start | 各予測バッチの開始時に呼び出されます。 |
on_predict_postprocess_end | 予測の後処理の終了時に呼び出されます。 |
on_predict_batch_end | 各予測バッチの終了時に呼び出されます。 |
on_predict_end | 予測プロセスの終了時に呼び出されます。 |
エクスポーターのコールバック#
| コールバック | 説明 |
|---|---|
on_export_start | エクスポートプロセスの開始時に呼び出されます。 |
on_export_end | エクスポートプロセスの終了時に呼び出されます。 |
よくある質問#
Ultralyticsのコールバックは、トレーニング、検証、推論、エクスポートなどのモデル操作における主要な段階でトリガーされるエントリーポイントです。ライブラリを変更せずに、処理の特定の箇所へカスタム機能を追加できます。操作の種類に応じて、各コールバックは
Trainer、Validator、Predictor、またはExporterオブジェクトを受け取ります。コールバックを使用するには、関数を定義し、
model.add_callback()メソッドを使ってモデルに追加します。以下は、予測中に追加情報を返す例です。from ultralytics import YOLO def on_predict_batch_end(predictor): """Handle prediction batch end by combining results with corresponding frames; modifies predictor results.""" _, image, _ = predictor.batch image = image if isinstance(image, list) else [image] predictor.results = zip(predictor.results, image) model = YOLO("yolo26n.pt") model.add_callback("on_predict_batch_end", on_predict_batch_end) for result, frame in model.predict(): passトレーニングプロセスの特定の段階にロジックを挿入して、Ultralytics のトレーニングルーチンをカスタマイズできます。Ultralytics YOLO には、
on_train_start、on_train_end、on_train_batch_endなど、さまざまなトレーニングコールバックが用意されており、カスタムメトリクス、処理、ログ記録を追加できます。各トレーニングエポックの終了時に、オプティマイザーの各パラメーターグループの学習率を記録する方法は次のとおりです。
from ultralytics import YOLO def log_learning_rates(trainer): """Print the current learning rates after each training epoch.""" print(f"Epoch {trainer.epoch + 1}: {trainer.lr}") model = YOLO("yolo26n.pt") model.add_callback("on_train_epoch_end", log_learning_rates) model.train(data="coco8.yaml", epochs=3)ヒントfreezeの使用時に、BatchNorm の統計情報を固定するためのコールバックは必要ありません。エポックの開始時に、トレーナーが固定されたレイヤーの BatchNorm レイヤーを自動的に eval モードに設定します。トレーニングコールバックを効果的に使用する方法について詳しくは、トレーニングガイドを参照してください。
検証コールバックを使用すると、モデル評価にカスタム処理、ロギング、指標計算を追加できます。
on_val_start、on_val_batch_end、on_val_endなどのコールバックは、検証の各段階にカスタムロジックを挿入するためのエントリーポイントを提供します。たとえば、最初の 3 つだけでなく、すべての検証バッチをプロットする方法は次のとおりです。
import inspect from ultralytics import YOLO def plot_samples(validator): frame = inspect.currentframe().f_back.f_back v = frame.f_locals validator.plot_val_samples(v["batch"], v["batch_i"]) validator.plot_predictions(v["batch"], v["preds"], v["batch_i"]) model = YOLO("yolo26n.pt") model.add_callback("on_val_batch_end", plot_samples) model.val(data="coco.yaml")検証プロセスにコールバックを組み込む方法について詳しくは、検証ガイドを参照してください。
Ultralytics YOLO の予測モードにカスタムコールバックをアタッチするには、コールバック関数を定義し、予測プロセスに登録します。一般的な予測コールバックには、
on_predict_start、on_predict_batch_end、on_predict_endがあります。これらを使うと、予測出力を変更したり、データのログ記録や結果の変換などの機能を追加したりできます。特定のクラスのオブジェクトが存在するかどうかに基づいて予測結果を保存するカスタムコールバックの例を示します。
from ultralytics import YOLO model = YOLO("yolo26n.pt") class_id = 2 def save_on_object(predictor): r = predictor.results[0] if class_id in r.boxes.cls: predictor.args.save = True else: predictor.args.save = False model.add_callback("on_predict_postprocess_end", save_on_object) results_stream = model("pedestrians.mp4", stream=True, save=True) for result in results_stream: passさらに詳しい使用方法については、詳細な手順と追加のカスタマイズオプションが記載された予測ガイドを参照してください。
Ultralytics YOLO は、トレーニング、検証、予測などの各フェーズを強化およびカスタマイズするために、さまざまな実用的なコールバック実装をサポートしています。実用例をいくつか紹介します。
- カスタム指標のロギング: トレーニングまたは検証のエポック終了時など、さまざまな段階で追加の指標を記録します。
- データ拡張: 予測またはトレーニングのバッチ中に、カスタムのデータ変換や拡張を実装します。
- 中間結果: さらなる分析や可視化のために、予測やフレームなどの中間結果を保存します。
例:
on_predict_batch_endを使用し、予測中にフレームと予測結果を結合します。from ultralytics import YOLO def on_predict_batch_end(predictor): """Combine prediction results with frames.""" _, image, _ = predictor.batch image = image if isinstance(image, list) else [image] predictor.results = zip(predictor.results, image) model = YOLO("yolo26n.pt") model.add_callback("on_predict_batch_end", on_predict_batch_end) for result, frame in model.predict(): passその他のオプションや例については、コールバックのソースコードを確認してください。
コメント15
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
drbilal216
Hi can i and how use callback to freeze initial layers for number of epochs and unfreeze after that, is there any builtin function for that? i used freeze builtin function but it freezes for all the epochs.
drbilal216
also, after certain epochs the change in model training is minimal can we use callback then to change lr, how and what parameter to change ?
Glenn JocherUltralytics@drbilal216 yes, you can use callbacks to freeze/unfreeze layers dynamically during training. Here's how to freeze initial layers for specific epochs then unfreeze them:
from ultralytics import YOLO def dynamic_freeze_callback(trainer): freeze_epochs = 10 # Freeze for first 10 epochs freeze_layers = 10 # Number of layers to freeze if trainer.epoch < freeze_epochs: # Freeze layers for i, (name, param) in enumerate(trainer.model.named_parameters()): if i < freeze_layers: param.requires_grad = False else: # Unfreeze all layers for param in trainer.model.parameters(): param.requires_grad = True model = YOLO("yolo11n.pt") model.add_callback("on_train_epoch_start", dynamic_freeze_callback) model.train(data="coco8.yaml", epochs=20)For dynamic learning rate adjustment when training plateaus, you can modify the scheduler within a callback:
def dynamic_lr_callback(trainer): if trainer.epoch > 50 and trainer.epoch % 10 == 0: # Every 10 epochs after epoch 50 for param_group in trainer.optimizer.param_groups: param_group['lr'] *= 0.9 # Reduce LR by 10% model.add_callback("on_train_epoch_end", dynamic_lr_callback)1drbilal216
@glenn-jocher Thanks for the code! I'm working on a low-quality PPE dataset. With a custom YAML, I improved YOLOv12n accuracy by 3%, and got similar results on YOLOv11n with better FPS.
The default Nano model lets me use pretrained=True, but custom architectures start from scratch. Still, I can reuse best.pt as pretrained weights on the same YAML later.
I'm now exploring argument tuning and callbacks for further improvements. I also tried freezing/unfreezing layers mid-training but saw no gains.
Lastly, I integrated Flash into YOLOv12, but I don’t see any sign that it’s being used during training (tested on Colab and A100 80GB-server).
jnance34
Hello,
I'm trying to implement a custom
on_pretrain_routine_endcallback with amodel.tune()call, but it appears that the Tuner class isn't adding my custom callback function to theTuner.callbackslist. Here's some pseudo code of what I'm trying to do:def my_custom_callback(trainer): print("I'm in my custom callback function!") model = YOLO("model/yolo11n.pt") model.add_callback('on_pretrain_routine_end', my_custom_function) model.tune(...) # Expect to see "I'm in my custom callback function" for each trial run...For some reason my custom callback function isn't getting called for each training run of the Tuner. Am I missing a step here? I've taken a look at the source code but don't see anything obviously wrong...
Thanks!
-James
RizwanMunawar
@jnance34 Hi! At the moment, callbacks are not supported for model.tone(...). You can find a complete list of all supported callbacks here: https://docs.ultralytics.com/usage/callbacks/#all-callbacks
ruslanraupoff
When I'm using single device add_callback works well but multi gpu's not working any solution for this?
Glenn JocherUltralytics@ruslanraupoff for multi-GPU training with callbacks, ensure your callback function is properly registered in all processes. When using DDP mode, callbacks need to be added before the training starts and should be compatible with distributed training environments. If you're experiencing issues, verify that your callback logic is thread-safe and doesn't rely on process-specific resources. For implementation details, refer to our callbacks documentation: https://docs.ultralytics.com/usage/callbacks
1
D3RK0
Hi, in the documentation above, I see that
predictor.batchis used, which I assume refers to the current batch of the predictor. Is there a similartrainer.batchfor a trainer? I need it in order to apply data augmentation during the training of my YOLOv8 classifier.D3RK0
I forgot to ask which (callback) event do I need to select?
Glenn JocherUltralytics(編集済み)@D3RK0 trainer callbacks only receive the
trainerobject, so the current batch is not available there astrainer.batch. To apply custom augmentation to each training batch, subclass your trainer (e.g.ClassificationTrainer) and overridepreprocess_batch(self, batch), which receives every training batch before the forward pass.D3RK0(編集済み)
@glenn-jocher Many thanks for your quick response!
I am dealing with following problem though:
Problem
When I do
trainer.batch, I get the following error:Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.3\plugins\python-ce\helpers\pydev\pydevd.py", line 1534, in _exec pydev_imports.execfile(file, globals, locals) # execute the script ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 397, in <module> main() File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 377, in main model.train(mode="classify", File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\model.py", line 802, in train self.trainer.train() File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 207, in train self._do_train(world_size) File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 368, in _do_train self.run_callbacks("on_train_batch_start") File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 168, in run_callbacks callback(self) File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 185, in batch_augmentation_callback batch = trainer.batch # Access the current batch ^^^^^^^^^^^^^ AttributeError: 'ClassificationTrainer' object has no attribute 'batch'My code
model = YOLO("yolov8m-cls.pt") model.add_callback("on_train_batch_start", batch_augmentation_callback) model.train(mode="classify", data=data_file_dir, epochs=args.n_epochs) # Where batch_augmentation_callback is my callback function def batch_augmentation_callback(trainer): batch = trainer.batch # This code line causes the error reported above images, labels = batch['img'], batch['label'] # More code below to create data augmentationContent of
trainerobject that is passed intobatch_augmentation_callback(my callback function)- trainer = {ClassificationTrainer} <ultralytics.models.yolo.classify.train.ClassificationTrainer object at 0x0000016929FA5010>
- accumulate = {int} 4
- amp = {bool} False
- args = {IterableSimpleNamespace} IterableSimpleNamespace(task='classify', mode='train', model='yolov8m-cls.pt', data='C:/Users/derk_/Documents/Universiteit/IRP...ugment='randaugment', erasing=0.4, crop_fraction=1.0, cfg=None, tracker='botsort.yaml', save_dir='C:\runs\classify\train53')
- batch_size = {int} 16
- best = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights/best.pt')
- best_fitness = {NoneType} None
- callbacks = {defaultdict: 25} defaultdict(<class 'list'>, {'on_pretrain_routine_start': [<function on_pretrain_routine_start at 0x0000016929C79440>, <functi...C7A2A0>, <function on_export_start at 0x000001692A55C220>], 'on_export_end': [<function on_export_end at 0x0000016929C7A340>]})
- csv = {WindowsPath} WindowsPath('C:/runs/classify/train53/results.csv')
- data = {dict: 5} {'names': {0: '1', 1: '10', 2: '100', 3: '101', 4: '102', 5: '11', 6: '12', 7: '13', 8: '14', 9: '15', 10: '16', 11: '17', 12: '18', 13: '19', 14: '2', 15: '20', 16: '21', 17: '22', 18: '23', 19: '24', 20: '25', 21: '26', 22: '27', 23: '28', 24: '29', 25:
- device = {device} device(type='cpu')
- ema = {ModelEMA} <ultralytics.utils.torch_utils.ModelEMA object at 0x000001692AC80C90>
- epoch = {int} 0
- epoch_time = {NoneType} None
- epoch_time_start = {float} 1731355033.8569636
- epochs = {int} 1
- fitness = {NoneType} None
- hub_session = {NoneType} None
- last = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights/last.pt')
- loss = {NoneType} None
- loss_names = {list: 1} ['loss']
- metrics = {dict: 3} {'metrics/accuracy_top1': 0, 'metrics/accuracy_top5': 0, 'val/loss': 0}
- model = {ClassificationModel} ClassificationModel(\n (model): Sequential(\n (0): Conv(\n (conv): Conv2d(3, 48, kernel_size=(3, 3), stride=(2, 2), padd...1)\n (drop): Dropout(p=0.0, inplace=True)\n (linear): Linear(in_features=1280, out_features=102, bias=True)\n )\n )\n)
- optimizer = {AdamW} AdamW (\nParameter Group 0\n amsgrad: False\n base_momentum: 0.85\n betas: (0.9499811807836418, 0.999)\n capturable: Fa... lr: 0.004018066447703833\n max_lr: 0.1\n max_momentum: 0.95\n maximize: False\n min_lr: 4e-07\n weight_decay: 0.0\n)
- plot_idx = {list: 6} [0, 1, 2, -3465, -3464, -3463]
- plots = {dict: 0} {}
- resume = {bool} False
- save_dir = {WindowsPath} WindowsPath('C:/runs/classify/train53')
- save_period = {int} 1
- scaler = {GradScaler} <torch.amp.grad_scaler.GradScaler object at 0x000001692921A0D0>
- scheduler = {OneCycleLR} <torch.optim.lr_scheduler.OneCycleLR object at 0x000001692ACF5210>
- start_epoch = {int} 0
- stop = {bool} False
- stopper = {EarlyStopping} <ultralytics.utils.torch_utils.EarlyStopping object at 0x000001692ACF7190>
- stride = {int} 32
- test_loader = {InfiniteDataLoader: 32} <ultralytics.data.build.InfiniteDataLoader object at 0x000001692AAD7B50>
- testset = {WindowsPath} WindowsPath('C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg/val')
- tloss = {NoneType} None
- train_loader = {InfiniteDataLoader: 385} <ultralytics.data.build.InfiniteDataLoader object at 0x00000169297FFDD0>
- train_time_start = {float} 1731355033.8569636
- trainset = {WindowsPath} WindowsPath('C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg/train')
- validator = {ClassificationValidator} <ultralytics.models.yolo.classify.val.ClassificationValidator object at 0x000001692AC80BD0>
- wdir = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights')
Question
If it is right that
trainer.batchdoes not exist (in this case), which other object in trainer - as listed above in the content of trainer - can I extract the current batch?
Glenn JocherUltralytics(編集済み)The
trainer.batchattribute does not exist in the current implementation, and iteratingtrainer.train_loaderinside a callback would draw a different batch rather than the current one. Instead, overridepreprocess_batch(self, batch)in a custom trainer subclass to modify each batch before it is used.D3RK0(編集済み)
@glenn-jocher Many thanks for answering!
Okay, I have been able to access the batches via
trainer.train_loaderand subsequently apply data augmentation to each batch. However, ...Problem
... assigning the batch back (see also the code below) to
trainer.train_loaderis not possible, as I get:trainer.train_loader[i] = batch ~~~~~~~~~~~~~~~~~~~~^^^ TypeError: 'InfiniteDataLoader' object does not support item assignmentCode
def batches_augmentation_callback(trainer): for i, batch in enumerate(trainer.train_loader): images, labels = batch['img'], batch['cls'] cutmix_or_mixup = LoadOxfordFlowerDataset.data_augmentation(n_classes_in_batch=args.n_classes) images, labels = cutmix_or_mixup(images, labels) batch = {"img": images, "cls": labels} trainer.train_loader[i] = batch # BUG: trainer.train_loader object does not support item assignmentQuestion
How can I return the augmented batch to the
trainerobject if assignment does not work?
Glenn JocherUltralyticsYou cannot directly assign to
trainer.train_loader. Instead, apply your augmentation within the loop and yield the modified batch back to the training process. Consider using a custom data loader or modifying the dataset directly for more complex augmentations.