2020-03-03 16:39:43 +00:00
|
|
|
r"""
|
|
|
|
Gradient Accumulator
|
|
|
|
====================
|
2020-04-05 09:38:52 +00:00
|
|
|
|
2020-03-03 16:39:43 +00:00
|
|
|
Change gradient accumulation factor according to scheduling.
|
2020-04-05 09:38:52 +00:00
|
|
|
|
2020-03-03 16:39:43 +00:00
|
|
|
"""
|
|
|
|
|
2020-03-19 13:14:29 +00:00
|
|
|
from pytorch_lightning.callbacks.base import Callback
|
2020-04-09 18:05:46 +00:00
|
|
|
from pytorch_lightning.utilities import rank_zero_warn
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
class GradientAccumulationScheduler(Callback):
|
|
|
|
r"""
|
|
|
|
Change gradient accumulation factor according to scheduling.
|
|
|
|
|
|
|
|
Args:
|
2020-03-06 17:00:05 +00:00
|
|
|
scheduling: scheduling in format {epoch: accumulation_factor}
|
2020-03-20 19:49:01 +00:00
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
Example::
|
|
|
|
|
2020-04-05 09:38:52 +00:00
|
|
|
>>> from pytorch_lightning import Trainer
|
|
|
|
>>> from pytorch_lightning.callbacks import GradientAccumulationScheduler
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
# at epoch 5 start accumulating every 2 batches
|
2020-04-05 09:38:52 +00:00
|
|
|
>>> accumulator = GradientAccumulationScheduler(scheduling={5: 2})
|
|
|
|
>>> trainer = Trainer(callbacks=[accumulator])
|
|
|
|
|
|
|
|
# alternatively, pass the scheduling dict directly to the Trainer
|
|
|
|
>>> trainer = Trainer(accumulate_grad_batches={5: 2})
|
2020-02-23 02:45:34 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, scheduling: dict):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
if not scheduling: # empty dict error
|
|
|
|
raise TypeError("Empty dict cannot be interpreted correct")
|
|
|
|
|
|
|
|
for key in scheduling:
|
|
|
|
if not isinstance(key, int) or not isinstance(scheduling[key], int):
|
2020-06-20 03:39:53 +00:00
|
|
|
raise TypeError("All epoches and accumulation factor must be integers")
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
minimal_epoch = min(scheduling.keys())
|
2020-06-20 03:39:53 +00:00
|
|
|
if minimal_epoch < 0:
|
2020-04-26 20:11:22 +00:00
|
|
|
raise IndexError(f"Epochs indexing from 1, epoch {minimal_epoch} cannot be interpreted correct")
|
2020-06-20 03:39:53 +00:00
|
|
|
if minimal_epoch != 0: # if user didnt define first epoch accumulation factor
|
|
|
|
scheduling.update({0: 1})
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
self.scheduling = scheduling
|
|
|
|
self.epochs = sorted(scheduling.keys())
|
|
|
|
|
2020-02-26 04:17:27 +00:00
|
|
|
def on_epoch_start(self, trainer, pl_module):
|
2020-06-16 10:33:41 +00:00
|
|
|
epoch = trainer.current_epoch
|
2020-02-23 02:45:34 +00:00
|
|
|
for i in reversed(range(len(self.epochs))):
|
|
|
|
if epoch >= self.epochs[i]:
|
|
|
|
trainer.accumulate_grad_batches = self.scheduling.get(self.epochs[i])
|
|
|
|
break
|