.. testsetup:: * from pytorch_lightning.trainer.trainer import Trainer from pytorch_lightning.callbacks.base import Callback
Lightning has a callback system to execute arbitrary code. Callbacks should capture NON-ESSENTIAL logic that is NOT required for your :class:`~pytorch_lightning.core.LightningModule` to run.
An overall Lightning system should have:
- Trainer for all engineering
- LightningModule for all research code.
- Callbacks for non-essential code.
Example:
.. testcode:: class MyPrintingCallback(Callback): def on_init_start(self, trainer): print('Starting to init trainer!') def on_init_end(self, trainer): print('trainer is init now') def on_train_end(self, trainer, pl_module): print('do something when training ends') trainer = Trainer(callbacks=[MyPrintingCallback()])
.. testoutput:: Starting to init trainer! trainer is init now
We successfully extended functionality without polluting our super clean :class:`~pytorch_lightning.core.LightningModule` research code.
The following are best practices when using/designing callbacks.
- Callbacks should be isolated in their functionality.
- Your callback should not rely on the behavior of other callbacks in order to work properly.
- Do not manually call methods from the callback.
- Directly calling methods (eg. on_validation_end) is strongly discouraged.
- Whenever possible, your callbacks should not depend on the order in which they are executed.
.. automodule:: pytorch_lightning.callbacks.base :noindex: :exclude-members: _del_model, _save_model, _abc_impl, check_monitor_top_k,
.. automodule:: pytorch_lightning.callbacks.early_stopping :noindex: :exclude-members: _del_model, _save_model, _abc_impl, check_monitor_top_k,
.. automodule:: pytorch_lightning.callbacks.gradient_accumulation_scheduler :noindex: :exclude-members: _del_model, _save_model, _abc_impl, check_monitor_top_k,
.. automodule:: pytorch_lightning.callbacks.lr_logger :noindex: :exclude-members: _extract_lr, _find_names
.. automodule:: pytorch_lightning.callbacks.model_checkpoint :noindex: :exclude-members: _del_model, _save_model, _abc_impl, check_monitor_top_k,
.. automodule:: pytorch_lightning.callbacks.progress :noindex: :exclude-members: