Package: gradient-accumulator
GradientAccumulatorSeemless gradient accumulation for TensorFlow 2GradientAccumulatorwas developed by SINTEF Health due to the lack of an easy-to-use method for gradient accumulation in TensorFlow 2.The package is available on PyPI and is compatible with and have been tested againstTensorFlow 2.2-2.12andPython 3.6-3.11, and works cross-platform (Ubuntu, Windows, macOS).Continuous integrationBuild TypeStatusCode coverageDocumentationsUnit testsInstallStable release from PyPI:pip install gradient-accumulatorOr from source:pip install git+https://github.com/andreped/GradientAccumulatorGetting startedA simple example to add gradient accumulation to an existing model is by:from gradient_accumulator import GradientAccumulateModel
from tensorflow.keras.models import Model

model = Model(...)
model = GradientAccumulateModel(accum_steps=4, inputs=model.input, outputs=model.output)Then simply use themodelas you normally would!In practice, using gradient accumulation with a custom pipeline might require some extra overhead and tricks to get working.For more information, see documentations which are hosted atgradientaccumulator.readthedocs.ioWhat?Gradient accumulation (GA) enables reduced GPU memory consumption through dividing a batch into smaller reduced batches, and performing gradient computation either in a distributing setting across multiple GPUs or sequentially on the same GPU. When the full batch is processed, the gradients are thenaccumulatedto produce the full batch gradient.Note that how we implemented gradient accumulation is slightly different from this illustration, as our design does not require having the entire batch in CPU memory. More information on what goes under the hood can be seen in thedocumentations.Why?In TensorFlow 2, there did not exist a plug-and-play method to use gradient accumulation with any custom pipeline. Hence, we have implemented two generic TF2-compatible approaches:MethodUsageGradientAccumulateModelmodel = GradientAccumulateModel(accum_steps=4, inputs=model.input, outputs=model.output)GradientAccumulateOptimizeropt = GradientAccumulateOptimizer(accum_steps=4, optimizer=tf.keras.optimizers.SGD(1e-2))Both approaches control how frequently the weigths are updated but in their own way. Approach (1) overrides thetrain_stepmethod of a given Model, whereas approach (2) wraps the optimizer. (1) is only compatible with single-GPU usage, whereas (2) also supports distributed training (multi-GPU).Our implementations enable theoreticallyinfinitely large batch size, withidentical memory consumptionas for a regular mini batch. If a single GPU is used, this comes at the cost of increased training runtime. Multiple GPUs could be used to improve runtime performance.TechniqueUsageBatch Normalizationlayer = AccumBatchNormalization(accum_steps=4)Adaptive Gradient Clippingmodel = GradientAccumulateModel(accum_steps=4, agc=True, inputs=model.input, outputs=model.output)Mixed precisionmodel = GradientAccumulateModel(accum_steps=4, mixed_precision=True, inputs=model.input, outputs=model.output)As batch normalization (BN) is not natively compatible with GA, we have implemented a custom BN layer which can be used as a drop-in replacement.Support for adaptive gradient clipping has been added as an alternative to BN.Mixed precision can also be utilized on both GPUs and TPUs.Multi-GPU distributed training using generic optimizer wrapper.For more information on usage, supported techniques, and examples, refer tothe documentations.ApplicationsHelland et al., Segmentation of glioblastomas in early post-operative multi-modal MRI with deep neural networks, arXiv, 2023,https://arxiv.org/abs/2304.08881Bouget et al., Raidionics: an open software for pre- and postoperative central nervous system tumor segmentation and standardized reporting, arXiv, 2023,https://arxiv.org/abs/2305.14351Pedersen et al., H2G-Net: A multi-resolution refinement approach for segmentation of breast cancer region in gigapixel histopathological images, Frontiers in Medicine, 2022,https://doi.org/10.3389/fmed.2022.971873AcknowledgementsThe gradient accumulator model wrapper is based on the implementation presented inthis threadon stack overflow. The adaptive gradient clipping method is based onthe implementation by @sayakpaul.
The optimizer wrapper is derived fromthe implementation by @fsx950223 and @stefan-falk.The documentations hostedherewas made possible by the incredibleRead The Docs teamwhich offer free documentation hosting!How to cite?If you used this package or found the project relevant in your research, please, include the following citation:@software{andre_pedersen_2023_7905351,
  author       = {André Pedersen and Tor-Arne Schmidt Nordmo and Javier Pérez de Frutos and David Bouget},
  title        = {andreped/GradientAccumulator: v0.5.0},
  month        = may,
  year         = 2023,
  publisher    = {Zenodo},
  version      = {v0.5.0},
  doi          = {10.5281/zenodo.7905351},
  url          = {https://doi.org/10.5281/zenodo.7905351}
}