Source code for objax.optimizer.momentum

# Copyright 2020 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.

__all__ = ['Momentum']

from typing import List, Optional

from jax import numpy as jn

from objax.module import Module, ModuleList
from objax.util import class_name
from objax.variable import TrainRef, StateVar, TrainVar, VarCollection

[docs]class Momentum(Module): """Momentum optimizer."""
[docs] def __init__(self, vc: VarCollection, momentum: float = 0.9, nesterov: bool = False): """Constructor for momentum optimizer class. Args: vc: collection of variables to optimize. momentum: the momentum hyperparameter. nesterov: bool indicating whether to use the Nesterov method. """ self.momentum = momentum self.nesterov = nesterov self.train_vars = ModuleList(TrainRef(x) for x in vc.subset(TrainVar)) self.m = ModuleList(StateVar(jn.zeros_like(x.value)) for x in self.train_vars)
[docs] def __call__(self, lr: float, grads: List[jn.ndarray], momentum: Optional[float] = None): """Updates variables and other state based on momentum (or Nesterov) SGD. Args: lr: the learning rate. grads: the gradients to apply. momentum: optional, override the default momentum. """ assert len(grads) == len(self.train_vars), 'Expecting as many gradients as trainable variables' if momentum is None: momentum = self.momentum if self.nesterov: for g, p, m in zip(grads, self.train_vars, self.m): m.value = g + momentum * m.value p.value -= lr * (g + momentum * m.value) else: for g, p, m in zip(grads, self.train_vars, self.m): m.value = g + momentum * m.value p.value -= lr * m.value
def __repr__(self): return f'{class_name(self)}(momentum={self.momentum}, nesterov={self.nesterov})'