Quasi-hyperbolic momentum and Adam for deep learning
Jerry Ma, Denis Yarats
Introduction
Stochastic gradient descent (SGD) serves as the optimizer of choice for many recent advances in deep learning across domains (Krizhevsky et al. 2012; He et al. 2016a; Gehring et al. 2017). SGD for deep learning is typically augmented with either the “heavy ball” momentum technique of Polyak 1964 or the accelerated gradient of Nesterov 1983. In the deterministic setting, these methods provably yield faster convergence in fairly general settings. In the stochastic setting, these methods lose many theoretical advantages. However, due to its implicit gradient averaging, momentum can confer the benefit of variance reduction, applying less noisy parameter updates than plain SGD. Recent work has explicitly shown the use of momentum as a variance reducer (Roux et al. 2018).
Starting with gradient variance reduction as an informal and speculative motivation, we introduce the quasi-hyperbolic momentum (QHM) optimization algorithm in Section 3. Put as simply as possible, QHM’s update rule is a weighted average of momentum’s and plain SGD’s update rule. We later propose a similar variant of Adam (QHAdam) in Section 5.
QHM is simple yet expressive. In Section 4, we connect QHM with plain SGD, momentum, Nesterov’s accelerated gradient, PID control algorithms (Recht 2018; An et al. 2018), synthesized Nesterov variants (Lessard et al. 2016), noise-robust momentum (Cyrus et al. 2018), Triple Momentum (Scoy et al. 2018), and least-squares acceleration of SGD (Kidambi et al. 2018). Such connections yield reciprocal benefits – these algorithms aid in analyzing QHM, and conversely QHM recovers many of these algorithms in a more efficient and conceptually simpler manner. We then characterize the set of optimization algorithms that QHM recovers.
In Section 6, we empirically demonstrate that QHM and QHAdam provide superior optimization in a variety of deep learning settings. We provide both comprehensive parameter sweep analyses on smaller models and case studies on large real-world models. We demonstrate improvements on strong (sometimes state-of-the-art) models simply by swapping out the vanilla algorithms with the QH counterpart. Notably, taking the WMT16 EN-DE translation model of Ott et al. 2018, we achieve a 40% improvement in stability, along with a new state-of-the-art result of 29.45 BLEU. We then offer some practical tips for QHM and QHAdam.
We provide errata for Kingma & Ba 2015, Recht 2018, and Kidambi et al. 2018. We also offer evidence that momentum often yields negligible improvement over plain SGD.
We emphasize QHM and QHAdam’s efficiency and conceptual simplicity. QHM has no extra overhead vs. Nesterov’s accelerated gradient, and QHAdam has very little overhead vs. Adam. Also, both algorithms are easily understood as an interpolation between two other well-known algorithms, so they are accessible to practitioners and can be tuned starting with existing practical intuitions. We believe that this contributes strongly to the algorithms’ practical promise.
Preliminaries
We begin with notation and a brief review of stochastic gradient descent (SGD) and momentum.
We consider optimization algorithms that perform a sequence of steps (indexed by ), updating at each step towards minimizing . For brevity, we write algorithms as “update rules”, which describe the algorithm’s behavior during a single step , rather than as full pseudocode. Update rules take this basic form (optionally with one or more auxiliary steps):
where is commonly called the “momentum buffer”. Note that recovers plain SGD.
The exponential discount factor controls how slowly the momentum buffer is updated. In the stochastic setting, also controls the variance of a normalized momentum buffer. A common rule of thumb for momentum is (Ruder 2016). Additionally, Kingma & Ba 2015 recommends for Adam, and is the default for Adam in both the PyTorch and TensorFlow frameworks (Paszke et al. 2017; Abadi et al. 2015).
In contrast to common formulations of momentum (Polyak 1964; Sutskever et al. 2013), we normalize, or “dampen”, the momentum buffer by in Eq. 1. This serves both to remove dependence of the update step magnitude on , and to allow the interpretation of as a weighted average of past gradients (and thus a gradient estimator). Of course, this also shrinks the updates by a factor of vs. common formulations; this is easily reversible with a corresponding increase to .
Algorithm: Quasi-hyperbolic momentum (QHM)
In this section, we propose and discuss the quasi-hyperbolic momentum (QHM) algorithm.
QHM introduces the immediate discount factor , encapsulating plain SGD () and momentum (). A self-evident interpretation of QHM is as a -weighted average of the momentum update step and the plain SGD update step.
Comparing Eq. 2 and Eq. 4, QHM may seem at first glance identical to momentum with discount factor . Section A.8 analytically demonstrates that this is not the case. We note that the expressive power of QHM intuitively comes from decoupling the momentum buffer’s discount factor () from the current gradient’s contribution to the update rule (). In contrast, momentum tightly couples the discount factor () and the current gradient’s contribution ().
QHM is originally motivated by an informal and speculative variance reduction analysis; for brevity, we provide the full details in Appendix A. The appendix also sheds some light on the nomenclature, adopted from the hyperbolic discounting work pioneered by Chung & Hernstein 1961, Phelps & Pollak 1968, and Laibson 1997 in consumer choice. We caution that “quasi-hyperbolic” does not directly relate to the geometry of hyperbolas. In short, the square bracket term in Eq. 4 can be viewed as a gradient estimator (modulo initialization bias). When , this is simply the momentum buffer . Increasing decreases the variance of the momentum buffer, but potentially at the cost of making it unusably “stale” (biased). QHM allows for the mitigation of this staleness by upweighting the current, unbiased gradient (i.e. setting ).
QHM, like momentum, requires 1 auxiliary buffer of memory. It also requires 1 in-place scalar-vector multiplication and 3 scaled vector additions per update step.
Connections to other algorithms
We now present numerous connections between QHM and other optimization algorithms. The common theme is that QHM recovers almost all of these algorithms, and thus is a highly interpretable and more efficient implementation of these algorithms. The first few subsections present these connections, Appendix C presents a deeper theoretical treatment of Section 4.2 through Section 4.4, which are largely narrative. Table 1 summarizes these connections, and Section 4.5 provides discussion.
Nesterov 1983’s accelerated gradient (NAG) can be viewed as a closely related cousin of momentum. In fact, replacing the term in Eq. 2 with yields NAG.
It follows from Eq. 4 that QHM recovers NAG with . This sheds light on the somewhat unintuitive NAG algorithm, providing a natural interpretation of NAG’s update rule as a -weighted average between momentum and plain SGD.
NAG’s compute/memory cost is equivalent to that of QHM.
2 PID control
Recht 2018 draws a strong connection between gradient-based optimization and PID control. We regurgitate the excellent exposition (with minor modifications) in Appendix B.
We fully relate QHM and PID in Section C.3. To summarize, PID is a superfamily of QHM. Viewing as a constant, QHM imposes a restriction on the ratio between and . Viewing as a free variable, however, QHM can recover nearly all PID coefficients.
Recht 2018 provides a transformation of variables that reduces the memory cost to 2 auxiliary buffers, and the compute cost to 1 in-place scalar-vector multiplication and 4 scaled vector additions per update step. This is still costlier than QHM.
In Appendix E, we briefly discuss another PID setting by An et al. 2018 and relate the resulting optimization algorithm to QHM. In short, the setting is degenerate as the P, I, and D terms are linearly dependent. Thus, QHM can recover the resulting PID control optimizer.
3 Synthesized Nesterov Variants (SNV)
Section 6 of Lessard et al. 2016 describes a “synthesized Nesterov variant” algorithm, which we call “SNV” for convenience. This algorithm is used to analyze and improve optimizer robustness under “relative deterministic noise” (i.e. multiplicative noise of the gradient).
We fully relate QHM and SNV in Section C.4. To summarize, QHM and SNV recover each other. By extension, QHM recovers the Robust Momentum method, which is a specific parameterization of SNV (Cyrus et al. 2018). Moreover, since Robust Momentum recovers the Triple Momentum of Scoy et al. 2018, QHM also recovers Triple Momentum.
SNV is costlier than QHM, requiring 2 auxiliary buffers and 5 scaled vector additions.
4 AccSGD
Jain et al. 2017 and Kidambi et al. 2018 point out various failures of momentum and NAG in the setting of stochastic least squares optimization. This motivates their proposal of the AccSGD algorithm, which yields faster convergence over momentum and NAG in certain least-squares regression settings. Here, we discuss the formulation of Kidambi et al. 2018.
AccSGD, parameterized by , , , and , uses the update rule:
We fully relate QHM and AccSGD in Section C.5. To summarize, QHM recovers AccSGD. In the reverse direction, AccSGD does not recover QHM; specifically, we disprove the claim in Kidambi et al. 2018 that AccSGD recovers NAG. Since QHM recovers NAG, AccSGD cannot fully recover QHM.
AccSGD, like QHM, requires 1 auxiliary buffer. Computationally, AccSGD is costlier, requiring 2 in-place scalar-vector multiplications and 4 scaled vector additions per update step.
5 Discussion
We note that various convergence results follow simply via these connections. In the deterministic (full-batch) case, since QHM recovers Triple Momentum, QHM also recovers the global linear convergence rate of for strongly convex, smooth loss functions. Here, is the ratio between the Lipschitz constant of and the strong convexity parameter of . For first-order methods, this is the fastest known global convergence rate for such functions. In the stochastic (minibatch) case, QHM’s recovery of AccSGD gives QHM the same convergence results as in Kidambi et al. 2018’s least-squares regression setting, of iterations for -approximation of the minimal loss.
These connections demonstrate that many two-state optimization algorithms are functionally similar or equivalent to each other. However, they are often implemented inefficiently and their parameterizations can be inaccessible to practitioners. QHM yields a highly accessible and efficient version of these algorithms.
In Appendix D, we characterize the set of two-state optimization algorithms recoverable by QHM. Our hope here is to provide future work with a routine conversion to QHM so that they may leverage the accessibility and efficiency benefits, as well as the many connections to other algorithms.
Going beyond a single momentum buffer, it is possible to recover many-state algorithms by linearly combining many momentum buffers (with different discount factors) in the update rule. However, we found in preliminary experiments that using multiple momentum buffers yields negligible value over using a single slow-decaying momentum buffer and setting an appropriate immediate discount – that is, using QHM with high and appropriate .
We note that the Aggregated Momentum (AggMo) algorithm (Lucas et al. 2018) precisely performs this linear combination of multiple momentum buffers. While AggMo takes a simple average of the buffers, an extended variant of AggMo allows for other linear combinations. This extended AggMo can be viewed as a many-state generalization of two-state algorithms (including QHM), recovering them when two buffers are used. Appendix H provides a supplemental discussion and empirical comparison of QHM and AggMo, corroborating our preliminary experiments’ findings.
Algorithm: QHAdam
The Adam optimizer (Kingma & Ba 2015) has enabled many compelling results in deep learning (Xu et al. 2015; Vaswani et al. 2017; Yu et al. 2018). We propose to replace both of Adam’s moment estimators with quasi-hyperbolic terms, and we name the resulting algorithm QHAdam.
QHAdam incurs four extra scaled vector additions over Adam.
We leave formal convergence analysis to future work. However, a couple of informal points are worth mentioning. Firstly, and can be reasoned about in a similar manner to QHM’s and . Secondly, when replacing Adam with QHAdam, setting and unchanged is usually reasonable if the original Adam training is stable. Thirdly, when Adam training is not stable, it is possible that setting can improve stability by imposing a tighter step size bound – Appendix F elaborates, disproving the step size bound claimed in Kingma & Ba 2015.
Experiments
We perform two categories of experiments: parameter sweeps and case studies. For brevity, all experimental settings are summarized in Table 2 and comprehensively detailed in Appendix I.
With parameter sweeps, we aim to comprehensively study the various parameterizations of the QH algorithms using relatively small models. We train for 90 epochs with size-64 minibatches. For QHM, we initialize and decay it 10-fold every 30 epochs. The sweep grid for QHM (encapsulating various parameterizations of plain SGD, momentum, and NAG) is:
For QHAdam, we fix , , , and , and sweep over and .
Motivated by the popular momentum/NAG “default” of , we select a QH “default” of and based on preliminary experimentation on the MNIST dataset (LeCun 1998) along with the intuitions from Appendix A. In the following figures, we show these defaults along with the globally optimal parameterizations.
Fig. 1 presents selected results of these sweep experiments (full results in Appendix J). Perhaps the most immediate observation is that the QH algorithms improve both training and validation metrics. Even the hardcoded default and handily outperforms the optimal parameterization of NAG or Adam in all settings. In some settings, there remains a large gap between the QH and vanilla algorithms at the end of training. In other settings, the gap shrinks to smaller levels. However, even for these latter settings, the QH algorithm converges much faster, suggesting that a more aggressive learning rate schedule can significantly reduce training time.
We note that in most of these experiments, there is little difference between the performance of plain SGD and NAG (particularly when compared to QHM). Although not shown in the figures, there is also little difference between plain SGD and momentum. This indicates that the benefit of momentum and NAG (in the common, unnormalized formulations) comes in large part from the increase in effective step size. We thus suspect that much of the folk wisdom about momentum’s benefits for SGD should instead be folk wisdom about using sensible learning rates. In contrast, QHM provides significant benefits without changing the effective step size.
2 Case studies
With case studies, we apply the QH algorithms to diverse settings, with (currently or recently) state-of-the-art models. Our case studies cover image recognition, language modeling, reinforcement learning, and neural machine translation. Each case study features a baseline setting and a QH setting, which are identical modulo the optimizer used. Results are presented in Fig. 2 and Table 3.
We train a ResNet152 model (He et al. 2016a) on the ILSVRC2012 dataset (Russakovsky et al. 2015). The baseline setting is nearly identical to the size-256 minibatch baseline in Goyal et al. 2017, using NAG with and a decaying learning rate schedule. The QH setting swaps out NAG for QHM, with and . Here, we did not sweep over alternate parameterizations.
Running 3 seeds, QHM plainly trains much faster than NAG, and QHM converges to a marginally superior validation error as well. We also train the model using plain SGD, again finding that plain SGD performs nearly as well as NAG throughout training. Although not shown, plain SGD in fact performs better than momentum. The validation loss curves for plain SGD, momentum, and NAG are indistinguishable throughout training, suggesting that momentum/NAG is not needed in Goyal et al. 2017.
Deep learning for NLP often features “spiky” gradient distributions (e.g. encountering rare words). We train a FConv language model (Dauphin et al. 2016) on the WikiText-103 dataset (Merity et al. 2016). The baseline setting precisely follows the original paper, using NAG with . The QH setting swaps out NAG for QHM, with and . 7 We suspect that high improves stability in the presense of spiky gradients, and QHM’s allows the use of high .
Running 10 seeds, QHM outperforms the NAG baseline on validation perplexity by half a point.
Reinforcement learning presents a challenging task for gradient-based optimization, since the objective is not stationary. QH algorithms provide a natural way of upweighting the most recent gradient. Here, we apply the TD3 algorithm (Fujimoto et al. 2018) to various MuJoCo environments (Todorov et al. 2012). The baseline precisely follows Fujimoto et al. 2018’s setup, which uses Adam with and . The QH setting swaps out Adam for QHAdam, with and other parameters identical. Here, we tried higher values of . Significantly increasing was not fruitful for either algorithm.
Running 10 seeds, QHAdam yields improvements in average reward on four environments out of seven tested, and virtually ties on another.
Many state-of-the-art neural machine translation (NMT) models are fragile to train. As in language modeling, the gradient distribution is often ‘‘spiky’’; thus, Adam training often fails to converge due to a very small number of large parameter updates. Refer to Appendix F for a more detailed theoretical treatment. Here, we empirically demonstrate that QHAdam improves both performance and robustness by using to control the maximum per-step update. We train a large transformer model (Vaswani et al. 2017) on the WMT16 English-German dataset. The baseline setting precisely follows the state-of-the-art setup of Ott et al. 2018, using and for Adam. The QH setting swaps out Adam for QHAdam, with , , , and . Here, we tried two other parameterizations (higher ) with marginal success.
Running 10 seeds, the Adam baseline explodes on 4 seeds. QHAdam is more robust, converging for all seeds. Ultimately, QHAdam yields a new state-of-the-art-result of 29.45 BLEU. Thus, we improve both the stability and performance of the state-of-the-art with a simple optimizer swap.
Discussion
We offer some practical suggestions for deep learning practitioners, particularly those who default to momentum, NAG, or Adam with as a rule of thumb:
Consider using QHM or QHAdam, instead of momentum, NAG, or Adam.
While QHM parameters should be tuned when feasible, a decent rule of thumb is to set and . QHAdam parameter selection is somewhat more situational, although as discussed in Section 5, and unchanged is usually reasonable when replacing a stable Adam optimizer with QHAdam.
Be mindful of learning rate differences between (unnormalized) momentum/NAG and QHM. Convert learning rates from the former to the latter via multiplication by . For example, momentum/NAG with and should be replaced by QHM with . This conversion is unnecessary for Adam, as it already normalizes all buffers.
2 Future work
This paper has only scratched the surface when it comes to empirical evaluation of QHM and QHAdam. Future work could apply the algorithms to other well-studied tasks and architectures, both to assess the extent of their performance gains in diverse domains, and to further develop insights into hyperparameter choice.
Effective hyperparameter autotuning methods can improve the practicality of any optimization algorithm. Thus, a useful direction for future work is to create an effective adapter, possibly based on techniques such as YellowFin (Zhang et al. 2017) or via continuous-time optimal control analysis, as in Li et al. 2017. Moreover, learning rate adaptation techniques such as Hypergradient Descent (Baydin et al. 2018) can be applied to both QHM and QHAdam.
Future work could develop convergence results for QHAdam. Convergence results for QHM in a reasonably general stochastic setting would also be appealing, although we are not aware of compelling analogous results for momentum or NAG.
Finally, momentum has been studied in the distributed, asynchronous setting, with some noting that the delays in asynchronous SGD are, in some sense, akin to adding momentum (Mitliagkas et al. 2016). As a result, the optimal momentum constant shrinks as more asynchronous workers are added to optimization. It would be interesting to extend these results to QHM, especially to disentagle the implicit effects of asynchrony on and .
3 Conclusion
QHM and QHAdam are computationally cheap, intuitive to interpret, and simple to implement. They can serve as excellent replacements for momentum/NAG and Adam in a variety of settings. In particular, they enable the use of high exponential discount factors (i.e. ) through the use of immediate discounting (i.e. ). QHM recovers numerous other algorithms in an efficient and accessible manner. Parameter sweep experiments and case studies demonstrate that the QH algorithms can handily outpace their vanilla counterparts. We hope that practitioners and researchers will find these algorithms both practically useful and interesting as a subject of further study.
We thank Aaron Defazio, Nicolas Loizou, Yann Olivier, Mark Tygert, and anonymous reviewers and commenters for insightful discussions and valuable suggestions.
References
Appendices
This paper’s appendices are ordered as follows:
Appendix A presents a view of momentum and QHM as discounted sums, and provides the original motivation for the development of QHM.
Appendix B regurgitates Recht 2018’s excellent exposition of gradient-based optimization as PID control, with minor modifications.
Appendix C presents analyses of various other algorithms, towards connecting them to QHM.
Appendix D describes the set of all two-state optimization algorithms recovered by QHM.
Appendix E briefly discusses a PID control optimization setting by An et al. 2018.
Appendix F derives a tight upper bound on the updates of Adam and QHAdam (consequently disproving the bound in Kingma & Ba 2015), then discusses the implications on training stability.
Appendix G provides miscellaneous derivations that do not cleanly fit in other sections.
Appendix H provides discussion and an empirical comparison of QHM and AggMo (Lucas et al. 2018).
Appendix I comprehensively describes the setup of this paper’s parameter sweep and case study experiments.
Appendix J comprehensively presents the results of this paper’s parameter sweep experiments.
Appendix A Discounted sum estimators (original variance reduction motivation for QHM)
We now provide an interpretation of the momentum buffer as a discounted sum estimator, seeking to motivate the QHM algorithm from a variance reduction perspective.
When for all , we call this a discounted sum average. When , we call this a discounted sum average (modulo initialization bias).
A.2 Exponential discounting and EWMA
For , we define the exponential discount function as:
and the exponentially weighted moving average as:
The EWMA is a discounted sum average (modulo initialization bias), so it can be viewed as an estimator of the expectation of a random variable if . Note that the momentum buffer from Eq. 1 is precisely an EWMA – specifically, .
It is well known that the exponential discount function is the only time-consistent (commonly “memoryless”), discount function – i.e. for any , the ratio depends only on . This is precisely why the EWMA can be tracked with no auxiliary memory – for example, as in momentum’s update rule.
A.3 EWMA as variance reduction
We now provide the following fact about the covariance of the EWMA when are random variables.
Assume that are independent random vectors, each with the covariance matrix . Then:
This means that arbitrary variance reduction of the EWMA is possible by increasing . For example, implies that the covariance is reduced to , and implies that the covariance is reduced to .
This provides an intuitive explanation of momentum as a variance reduction technique. Assuming that the momentum buffer is normalized (and thus interpretable as an estimator of the gradient), applying momentum will reduce the variance of the update steps, with higher leading to more variance reduction.
However, the flip side is that higher induces more bias (informally, “staleness”) in the momentum buffer with respect to the true gradient, as the momentum buffer becomes extremely slow to update. Thus, the question arises: can we achieve variance reduction while guaranteeing that recent gradients contribute significantly to the update step? For this, we must introduce time-inconsistency.
A.4 (Pure) hyperbolic discounting and HWMA
Hyperbolic discounting, first proposed by Chung & Hernstein 1961, is the classical time-inconsistent discount function in consumer choice. It is commonly used to model individual behaviors such as impatience. We consider its use in the setting of stochastic optimization (in place of the EWMA buffer of momentum).
For constants , we define the hyperbolic discount function as: Slightly adapted from the original formulation.
and the hyperbolic weighted moving average as:
Note that the hyperbolic discount function is time-inconsistent, since:
Unlike the EWMA, the HWMA is not a discounted sum average – in fact, holds regardless of choice of or . Thus, to use an HWMA of gradients in an optimization algorithm, (or the learning rate ) must be decayed at a logarithmic rate. More concerning, however, is the computational inefficiency of the HWMA; specifically, the sum must be recomputed from scratch at each iteration from all past gradients. This is unacceptable for use in most practical applications.
However, in preliminary stochastic optimization experiments, we did observe a marked benefit of HWMA over EWMA (i.e. momentum), limiting the number of past gradients used for tractability. This indicates that time-inconsistency might be a useful property to have in a stochastic optimizer.
A.5 Quasi-hyperbolic discounting and QHWMA
Quasi-hyperbolic discounting, proposed by Phelps & Pollak 1968 and popularized in consumer choice by Laibson 1997, seeks to qualitatively approximate the time-inconsistency of hyperbolic discounting by applying a discontinuous “upweighting” of the current step. Its tractability has resulted in much wider adoption in consumer choice vs. pure hyperbolic discounting, and we find that it is also more suited for use in practical optimization.
and the quasi-hyperbolic weighted moving average as:
The QHWMA, like the EWMA, is a discounted sum average (modulo initialization bias), so it can also be viewed as an estimator under the same assumptions.
When , the QHWMA is precisely the EWMA (with identical ), and the quasi-hyperbolic discount function is precisely the exponential discount function (and thus time-consistent). When , the quasi-hyperbolic discount function, like the hyperbolic discount function, is time-inconsistent since:
depends on both and ; specifically, yields a different ratio than .
Note from Eq. 5 that the QHWMA is a -weighted average of the EWMA (with identical ) and . This means that the QHWMA can be easily computed online by simply keeping track of the EWMA, thus requiring no additional memory.
A.6 Variance of QHWMA
We now characterize the variance of a QHWMA using this fact:
Assume that are independent random vectors, each with the covariance matrix . Then:
is essentially a scaling factor for the covariance of the QHWMA. It can be verified that decreases (thus inducing variance reduction) with both increasing and increasing .
A.7 Motivating QHM
This leads to our motivation for QHM, which simply replaces the EWMA momentum buffer with a QHWMA. Starting with any momentum parameterization ( and ), can be increased towards variance reduction (i.e. lowering ). Then, can be decreased to make the QHWMA less biased as a gradient estimator, thus mitigating the aforementioned “staleness” problem. Note, however, that since decreasing will also increase , we cannot simply decrease to zero. Specifically, any imposes a tight lower bound of on , regardless of choice of .
A.8 Momentum and QHM update rules
For completeness, we explicitly write the update rules for the momentum and QHM algorithms.
which can be efficiently written using an auxiliary buffer as:
which can be efficiently written using an auxiliary buffer as:
Comparing Eq. 2 and Eq. 4, QHM may seem at first glance identical to momentum with discount factor . However, replacing the in Eq. 6 with yields:
which plainly differs from Eq. 7 – most notably, in the exponential discount factor () for past gradients. Thus, momentum with discount factor does not recover QHM.
A.9 Related work in variance reduction
Section 4 presents numerous connections to other optimization algorithms that shed light on both deterministic and stochastic convergence properties of QHM. However, we do not formally analyze the convergence properties of QHM from a variance reduction standpoint; this remains future work. Here, we briefly discuss other work in variance reduction.
Recently, much effort has been devoted towards reducing the variance of the stochastic gradients used in optimization algorithms. Perhaps the most widely-studied setting is the “finite sum”, or offline, stochastic optimization setting. Methods analyzed in the finite-sum setting include SAG (Schmidt et al. 2013), SAGA (Defazio et al. 2014), SVRG (Johnson & Zhang 2013), FSVRG (Shang et al. 2017), Katyusha (Allen-Zhu 2017), and others. We do not comment in detail on the finite sum setting due to its limited practical applicability to large-scale deep learning; for a fuller discussion of such methods, see Kidambi et al. 2018.
Some work in variance reduction has drawn an explicit connection to momentum. For example, Roux et al. 2018 propose a method involving Bayesian updates of gradient estimates, which induces adaptive gradient averaging. The authors note that this method boils down to momentum with an adaptive .
Appendix B PID controllers and optimization
We follow Recht 2018 in describing the connection between PID control and gradient-based optimization.
We slightly adapt the setting from Aaström & Hägglund 1995. denotes time. There is a setpoint (i.e. target state), , and a process variable (i.e. current state), . The error of the system is defined as . A “controller” outputs a control signal , usually towards the goal of making the error zero. The controller’s choice of affects in some unspecified manner.
A PID controller, parameterized by , , and , uses the control function:
Here, the terms in the square brackets are typically referred to as the P, I, and D terms, respectively.
In discrete time, the setpoint, process variable, and error are trivially discretized as , , and , respectively. The I term, which we label , is discretized as:
The D term, which we label , could be discretized as (first differences). However, a low-pass filter is often applied to mitigate noise, thus resulting in:
We simplify exposition by considering , , and to be .
Finally, the PID control function Eq. 8 is trivially discretized as:
Recht 2018 relates optimization to PID control as follows:
That is, the process variable is the stochastic gradient, the controller’s goal is to make this gradient zero, and the controller achieves this by choosing the next step’s model parameters according to the update rule . The update rule for a PID control optimizer is thus:
Recht demonstrates that PID in this setting encapsulates gradient descent, momentum, and NAG; for example, gradient descent is recovered when and .
Finally, to provide some additional intuition, we can state the following fact about the D term ():
Thus, the D term is simply a weighted sum of an EWMA of gradients (i.e. momentum buffer) and the current gradient, and a PID control optimizer’s output is simply a weighted sum of the momentum buffer, the current gradient, and the sum of all past gradients.
Appendix C Connections to other algorithms (in-depth)
This appendix presents a deeper theoretical treatment of Section 4.2 through Section 4.4, deriving and discussing connections between QHM and various other optimization algorithms.
For convenience, we impose the restriction that the output can only depend on the state . Then, for analytical purposes, the optimizer can be written as the following update rule:
where denotes the size- zero vector, denotes throwaway values, and denotes vector stacking.
Then, for , we can write in terms of the initial state and all past gradients, using the last row of various matrix powers of :
C.2 QHM
The internal state of QHM includes two buffers: (momentum buffer) and (model parameters).
The transition matrix , mapping from to , is:
For , routine computation yields the last row of the -th matrix power:
Applying Eq. 10, the optimizer state can be written as:
In the typical case of , we have:
C.3 PID
Recht 2018 draws a strong connection between gradient-based optimization and PID control. We regurgitate the excellent exposition (with minor modifications) in Appendix B.
The transition matrix , mapping from to , is:
For , routine computation yields the last row of the -th matrix power:
Applying Eq. 10, the optimizer state can be written as:
In the typical case of , we have:
Then, equating with Eq. 11, we have that QHM is PID with: This is inconsistent with Recht 2018’s derivation by a factor of in and in . While is explainable as the difference between a normalized and unnormalized momentum buffer, we suspect that the extra factor of in is a mistake in the original derivation.
Viewing as a constant, the following restriction holds on the PID coefficients that QHM can recover:
This restriction is looser than those for plain SGD (which has the additional restriction ), momentum (which has the additional restriction ), and NAG (which has the additional restriction ).
Viewing as a hyperparameter, QHM can recover all PID coefficients except when (i.e. P, D, or PD controller), or (i.e. PI controller).
To summarize, PID is a superfamily of QHM. Viewing as a constant, QHM imposes a restriction on the ratio between and . Viewing as a free variable, however, QHM can recover nearly all PID coefficients.
C.4 SNV
Section 6 of Lessard et al. 2016 describes a ‘‘synthesized Nesterov variant’’ algorithm, which we call ‘‘SNV’’ for convenience. This algorithm is used to analyze and improve optimizer robustness under ‘‘relative deterministic noise’’ (i.e. multiplicative noise of the gradient). This is similar to the vanishing gradient assumption used in Loizou & Richtárik 2017, which removes the need to consider variance reduction of the gradient.
The internal state of a SNV optimizer includes two buffers: and .
The transition matrix , mapping from to , is:
For , routine computation gives us the last row of the -th matrix power:
Applying Eq. 10, the optimizer state can be written as:
Initialize . The optimizer state is:
Then, equating with Eq. 11, we have that QHM is SNV with:
To summarize, QHM and SNV recover each other. By extension, QHM recovers the Robust Momentum method, which is a specific parameterization of SNV (Cyrus et al. 2018). Moreover, since Robust Momentum recovers the Triple Momentum of Scoy et al. 2018, QHM also recovers Triple Momentum.
C.5 AccSGD
Jain et al. 2017 and Kidambi et al. 2018 point out various failures of momentum and NAG in the setting of stochastic least squares optimization. This motivates their proposal of the AccSGD algorithm, which yields faster convergence over momentum and NAG in certain least-squares regression settings. Here, we discuss the formulation of Kidambi et al. 2018.
AccSGD, parameterized by , , , and , uses the update rule:
The internal state of an AccSGD optimizer includes two buffers: (a buffer) and (the iterate, identical to ).
The transition matrix , mapping from to , is:
For , routine computation gives us the last row of the -th matrix power:
Applying Eq. 10, the optimizer state can be written as:
Fix , and initialize . The optimizer state is:
Then, equating with Eq. 11, we have that QHM is AccSGD with:
Based on the above analysis, NAG (i.e. ) is recovered when . Empirical simulations confirm this finding. This disproves the claim in Kidambi et al. 2018 that AccSGD recovers NAG when . In fact, we demonstrate that AccSGD cannot recover NAG at all. For and the aforementioned value of , we have that :
Since AccSGD requires that and that The recommended value for is 0.7 (Kidambi et al. 2018)., AccSGD cannot recover NAG.
To summarize, QHM recovers AccSGD. In the reverse direction, AccSGD does not recover QHM; specifically, we disprove the claim in Kidambi et al. 2018 that AccSGD recovers NAG. Since QHM recovers NAG, AccSGD cannot fully recover QHM.
Appendix D General two-state optimizer
To simplify further derivations we diagonalize as:
If , , , , , and , then QHM implements the TSO optimizer with:
We can write down the unrolled TSO update rule for , as follows:
Thus, the unrolled update rule for QHM takes the following form:
Now we match the corresponding coefficients in both of the update rules to establish dependencies:
By solving the first equation we can establish values for , , and :
Per our assumption and , we can recover the following relationships:
We can solve the second equation to find :
Given that and , we can simplify:
Appendix E An alternative PID setting
We very briefly comment on An et al. 2018’s PID control setting.
An et al. 2018’s PID control optimizer, parameterized by , uses the following update rule: The exponential discount is in the original paper; we use to avoid confusion.
This setting departs somewhat from typical PID control, in that the signal controls the derivative of the controller’s output (i.e. ) rather than the output itself (i.e. ). To avoid parameter blowup, this formulation necessitates the addition of exponential decay to the I term, with discount factor . One final oddity is that the D term () calculates the negation of the derivative.
The I term thus becomes the momentum buffer. However, recall from B.1 that the D term is a weighted sum of the momentum buffer and the P term. It follows that the D term is a weighted sum of the P and I terms, and that this setting is degenerate (either “PI” or “PD”).
As a consequence, the proposed PID algorithm of An et al. 2018 is less expressive than that of Recht 2018. Specifically, applying B.1 demonstrates a mapping into QHM:
This PID control optimizer is costlier than QHM. It requires 2 auxiliary buffers of memory. Computationally, it requires 2 in-place scalar-vector multiplications and 5 scaled vector additions per update step.
Appendix F (QH)Adam’s update bound
This appendix elaborates on Adam and QHAdam’s stability properties through the lens of a step size upper bound.
It is well known that the training process for deep learning models can often ‘‘explode’’ due to a very small number of large parameter updates. With Adam, these large updates can occur if there exist parameters whose stochastic gradients are almost always near zero but incur rare ‘‘spikes’’. Somewhat more concretely, a stochastic gradient is “spiky” if its distribution has extremely large higher-order cumulants relative to its typical magnitudes.. This is because the square root of the second moment estimate, used in normalizing the gradient for the update step, will be far below the magnitude of these spikes.
There are three main ways to address this instability:
Firstly, one can simply decrease the learning rate . However, this may be undesirable due to slower training.
Secondly, one can increase the hyperparameter. However, the appropriate setting of depends on the exact magnitudes of these gradient spikes, which is often unknown. Setting too high effectively turns Adam into SGD. Thus, setting often reduces to guesswork.
Thirdly, one can clip gradients. However, the appropriate magnitude of the gradient clipping also depends on the stochastic gradient distribution. Thus, this solution also involves a fair amount of guesswork.
However, Adam does provide a useful guarantee – unlike SGD, Adam has an upper bound on the per-step update (Kingma & Ba 2015). This upper bound is independent of the gradient distribution (or even temporal correlation), depending only on the hyperparameters , , and . Thus, no matter the gradient distribution, Adam will restrict the magnitude of the per-step updates to some known constant. Kingma & Ba 2015 intuitively describe this bound as “establishing a trust region around the current parameter value”.
We show that the step size upper bound claimed in Section 2.1 of Kingma & Ba 2015 is incorrect, by providing the correct tight bound for both Adam and QHAdam. We then demonstrate that with QHAdam, one can lower the maximum per-step update (and thus improve stability) simply by lowering to be below 1.
We make two simplifications. Firstly, we fix . The analysis with free follows the same approach but is somewhat messier. Secondly, we remove the bias correction of the moment estimators (i.e. we use and ).
In this setting, QHAdam applies the following update rule:
F.2 Implicit update bound
We now bound QHAdam’s update (before scaling by ) by a constant dependent only on , , , and :
We perform the following simplification of Eq. 12 and Eq. 13:
Plugging the values of from Eq. 17 into Eq. 14 and Eq. 15 yields:
The desired result follows immediately. ∎
Consider the limit case of . Then, the bound in F.1 simplifies to:
For vanilla Adam (i.e. ), Eq. 18 simplifies further to:
Note that since the bound in Eq. 19 is tight, this result contradicts the claim in Section 2.1 of Kingma & Ba 2015 that Adam’s per-coordinate step size is bounded above by . The difference can be rather large – for example, for the recommended Adam parameters of and , Kingma & Ba 2015 claim an upper bound of , while Eq. 19 implies a tight bound of . In the following discussion, we use the correct bounds from Eq. 18 and Eq. 19.
F.3 Discussion
The recommended vanilla Adam setting of in Kingma & Ba 2015 makes the right-hand side of Eq. 19 to be large, and various work has employed Adam with a significantly lower ; e.g. 0.98 (Vaswani et al. 2017; Ott et al. 2018). We performed experiments on these models indicating that increasing far beyond 0.98 led to training explosion. We suspect that these instability issues are especially prevalent in settings with rare inputs or labels, such as machine translation. Decreasing is undesirable, often slowing down training. In proposing the AdamNC algorithm, Reddi et al. 2018 suggests that should be high to capture a sufficiently long history of past gradients. Moving from Adam to QHAdam, an alternative solution is to decrease to be below 1. This decreases the right-hand side of Eq. 18, up to a point, and thus imposes a tighter constraint on the magnitudes of updates than the vanilla Adam setting of . Fig. 3 shows an example of this phenomenon using a fixed , , and .
Appendix G Miscellaneous derivations
This appendix provides miscellaneous derivations that do not cleanly fit elsewhere.
Due to the independence assumption, the covariance matrix of the QHWMA for is simply:
The desired result follows immediately. ∎
We expand as follows, recalling that :
We then proceed by separating out the sum in Eq. 20, recalling that :
The desired result follows by substituting into Eq. 21. ∎
Appendix H QHM and Aggregated Momentum
We perform a brief empirical comparison of QHM and Aggregated Momentum (AggMo), proposed by Lucas et al. 2018. In short, we find that for an autoencoder task, we can take the optimal parameterization of AggMo from an extensive parameter sweep, and from that we can construct a QHM parameterization by hand which outperforms the optimal AggMo parameterization.
AggMo is a many-state optimizer that aggregates multiple momentum buffers in its update rule.
Intuitively, AggMo maintains unnormalized momentum buffers with different discount factors and uses the average of these buffers in the update rule.
H.2 Empirical comparison of QHM and AggMo
We perform the autoencoder experiments of Lucas et al. 2018 using the authors’ implementation, https://github.com/AtheMathmo/AggMo with two changes:
We replace the MNIST dataset (LeCun 1998) with the richer digits subset of the EMNIST dataset (Cohen et al. 2017). We hold out 10% of the training dataset for validation.
We change the minibatch size from 200 to 256 for computational efficiency.
Lucas et al. 2018 conduct a sweep over parameterizations of AggMo. Performing the same sweep, we find that the best parameterization of AggMo uses discount factors and learning rate . We name this parameterization “AggMo-Best”.
We now apply intuition to convert AggMo-Best into a QHM parameterization, which we name “QHM-Converted”. We calculate the effective step size of AggMo-Best:
We round up and use as the learning rate for QHM-Converted.
From Section 7.1, our rule of thumb for QHM is and . However, noting that this rule of thumb is toward replacing momentum/NAG with discount factor 0.9, and observing that the best NAG parameterization reported by Lucas et al. 2018 uses discount factor 0.99, we instead use and for QHM-Converted.
In summary, the parameterization of QHM-Converted is , , and , and no optimization or parameter sweeps on this task were performed to construct this parameterization.
Fig. 4 and Table 4 present the performance of AggMo-Best and QHM-Converted on the autoencoder task. QHM-Converted outperforms AggMo-Best on the mean squared error (MSE) metric over the training, validation, and testing datasets.
H.3 Discussion
To recap, we take the optimal AggMo parameterization from an extensive sweep, we convert that parameterization by hand to one for QHM, and we find that the latter outperforms the former on this autoencoder task.
These results indicate that using multiple momentum buffers with an arbitrary weighting scheme (i.e. AggMo with ) provides negligible benefit over using a single slow-decaying momentum buffer with an appropriate weight (i.e. QHM with high and appropriate ).
Lucas et al. 2018 offer an interpretation of AggMo as passive damping for physical systems. In this interpretation, fast-decaying momentum buffers “dampen” the oscillations of slow-decaying momentum buffers by providing velocity in an opposite direction.
In this context and considering these results, we conjecture that the current gradient already provides adequate damping for a slow-decaying momentum buffer, and that the damping provided by additional momentum buffers is of marginal value.
Lucas et al. 2018 motivate this extension by the recovery of NAG. In fact, we observe that this extension, with and discount factors , recovers QHM as well.
In independent preliminary experiments on different tasks, we found that various alternate weighting schemes of multiple momentum buffers (i.e. various parameterizations of extended AggMo with ) did not result in material improvements over the single momentum buffer. However, this preliminary investigation was neither rigorous nor conclusive. Lucas et al. 2018 do not empirically explore these alternate weighting schemes, and it is unclear how to do so both comprehensively and efficiently, since the number of hyperparameters scales linearly with the number of momentum buffers .
Toward improving the usability of extended AggMo, we suggest as future work to investigate theoretically grounded or empirically tractable methods to determine good weighting schemes for extended AggMo. However, given the added costs and complexity of AggMo (both standard and extended), we surmise in the meantime that QHM may be preferable for most practical applications.
Appendix I Full details of experimental setup
All experiments use Python 3.7 and PyTorch 0.4.1 (Paszke et al. 2017). Experiments are run on a mix of NVIDIA P100 and V100 GPUs, along with a mix of CUDA 9.0 and 9.2.
I.1 Parameter sweep experiments
Training occurs over 90 epochs (minibatch size 64). The first epoch uses linear warmup of the learning rate (i.e. starts from zero and grows to its “regular” value by the end of the epoch). Each training run uses a single GPU.
Each parameterization is run 3 times with different seeds, and we report training loss, training top-1 error, and validation top-1 error.
We use a step decay schedule for the learning rate: . That is, the first 30 epochs use , the next 30 epochs use , and the final 30 epochs use . These learning rates may seem high, but recall that the effective step size is identical to that of “typical”, unnormalized momentum/NAG with and .
We sweep over and using the following two-dimensional grid:
Note that this grid encapsulates numerous parameterizations of plain SGD, momentum, and NAG (specifically, all parameterizations with the values enumerated above).
We fix , , and , as suggested in Kingma & Ba 2015. We also fix .
We sweep over and using the same grid as for QHM’s and .
I.1.1 Experiment: Logistic-EMNIST-QHM
The model is multinomial logistic regression with pixel vector input.
The task is digit recognition over the EMNIST dataset – specifically, the digits subset (Cohen et al. 2017).
The model is optimized with QHM. The optimization objective is cross-entropy loss, plus L2 regularization with coefficient .
I.1.2 Experiment: Logistic-EMNIST-QHAdam
The model is optimized with QHAdam. The optimization objective is the same as in Logistic-EMNIST-QHM.
I.1.3 Experiment: MLP-EMNIST-QHM
The model is a multilayer perceptron (specifically, 3 layer feed forward network) with pixel vector input. The hidden layer sizes are 200, 100, and 50 units, and all hidden units are non-linearities. The final layer is followed by softmax.
I.1.4 Experiment: MLP-EMNIST-QHAdam
I.1.5 Experiment: RN18-CIFAR10-QHM
The model is a 18-layer convolutional residual network with preactivations (He et al. 2016b).
The task is image recognition on the CIFAR-10 dataset (Krizhevsky 2009).
The model is optimized with QHM. The optimization objective is cross-entropy loss, plus L2 regularization with coefficient .
The implementation generally follows Liu 2017. Data augmentation includes horizontal flipping at random, as well as random 32-pixel crops with 4-pixel padding. For batch normalization (Ioffe & Szegedy 2015), we use online calculation of moments with exponential decay.
I.1.6 Experiment: RN50-ImageNet-QHM
The model is a 50-layer convolutional residual network (He et al. 2016a).
The task is image recognition on the ILSVRC2012 (“ImageNet”) 1000-class dataset (Russakovsky et al. 2015).
The model is optimized with QHM. The optimization objective is cross-entropy loss, plus L2 regularization with coefficient .
The implementation generally follows Paszke et al. 2016. Data augmentation includes horizontal flipping at random, as well as random 224-pixel crops. Validation is performed on 224-pixel center crops. For batch normalization, we use online calculation of moments with exponential decay. The model is trained with half-precision floating point.
I.2 Case studies
The model is a 152-layer convolutional residual network (He et al. 2016a).
We use the baseline configuration (NAG with size-256 minibatches) described in Goyal et al. 2017. Specifically, the learning rate schedule is for the first 30 epochs, for the next 30 epochs, for the next 20 epochs, and for the final 10 epochs. The optimization objective is cross-entropy loss, plus L2 regularization with coefficient . The only departure from Goyal et al. 2017 is that we employ a first-epoch linear warmup of (as in the parameter sweep experiments).
The non-baseline optimizer is QHM with and . Following Section 7.1, we increase the learning rate () 10-fold. All other details are identical to the baseline.
For each optimizer, we run 3 seeds and report validation top-1 error.
See RN50-ImageNet-QHM for implementation details.
I.2.2 Experiment: FConvLM-WikiText103-QHM
The model is the GCNN-14 variant of the gated convolutional language model described in Dauphin et al. 2016.
The task is language modeling on the WikiText-103 language dataset (Merity et al. 2016).
For the baseline, we use the configuration described in Dauphin et al. 2016. Specifically, the model is optimized with 60 epochs of NAG (). We initialize the learning rate to , and we halve it when validation loss begins to increase. The optimization objective is adaptive cross-entropy, plus direct weight decay with coefficient . We also clip gradient norm with maximum norm of 0.1.
The non-baseline optimizer is QHM with and . Following Section 7.1, we increase the initial learning rate () 100-fold. All other details are identical to the baseline.
For each optimizer, we run 10 seeds and report validation perplexity.
The implementation is exactly that of fairseq-py (Gehring et al. 2017). We train each model on 8 GPUs with half-precision floating point.
I.2.3 Experiment: TD3-MuJoCo-QHAdam
We use the Twin Delayed Deep Deterministic Policy Gradients (TD3) algorithm (Fujimoto et al. 2018) for actor/critic learning. Both the actor and the critic are represented as multilayer perceptrons.
We use a suite of MuJoCo continuous control tasks (Todorov et al. 2012). In particular, we perform evaluation on the following environments: HalfCheetah, Hopper, Walker2d, Ant, Reacher, InvertedPendulum, and InvertedDoublePendulum.
For the baseline, we use Adam with the default parameters (, , , and ) as in Fujimoto et al. 2018. We train for iterations.
The non-baseline optimizer is QHAdam. We set , , and otherwise leave the baseline setting unchanged.
For each optimizer, we run 10 seeds. For each seed, we report average reward (on 10 episodes) every 5000 iterations of training, following Fujimoto et al. 2018.
We use Fujimoto et al. 2018’s open-sourced implementation https://github.com/sfujim/TD3, along with version 2 of OpenAI Gym (Brockman et al. 2016).
I.2.4 Experiment: TF-WMT16ENDE-QHAdam
We use a Transformer-based model (Vaswani et al. 2017) described in Ott et al. 2018.
We train our models on a filtered version of the WMT16 English-German machine translation dataset as in Vaswani et al. 2017, and evaluate on newstest14 for English-German. Our evaluation setup is identical to the one in Ott et al. 2018.
For the baseline, we use Adam (, , and ) as in Ott et al. 2018, training over epochs. We use the same learning rate schedule as in Vaswani et al. 2017 and Ott et al. 2018. Specifically, we increase the learning rate from to linearly for 4000 steps, then decay it proportionally to the inverse square root of the number of steps. We optimize the label smoothed cross-entropy loss as in Vaswani et al. 2017, with label smoothing of 0.1.
We use QHAdam (, , , , and ) as a non-baseline optimizer. The other settings are identical to the baseline.
For each optimizer, we run 10 seeds and report validation perplexity and validation BLEU scores. We observe that 4 seeds for the baseline Adam optimizer “explode” (fail to converge). Thus, we only consider the 6 best seeds for each optimizer.
We use Ott et al. 2018’s open-sourced implementation in fairseq-py (Gehring et al. 2017). We train each model on 8 GPUs with half-precision floating point. Note that Ott et al. 2018 uses 128 GPUs; to eliminate this discrepancy and precisely reproduce the training environment, we accumulate gradients over 16 minibatches before each optimization step.
Appendix J Full parameter sweep results
Fig. 5 shows summary graphs for all parameter sweep experiments. These summary graphs display selected parameterizations and optimal parameterizations of both the vanilla and QH algorithms. Full details of experimental settings can be found in Appendix I.
Since each experimental setting contains nearly 200 parameterizations with 3 seeds each, we cannot fully present the data with graphs or tables. Thus, we provide data files describing all runs in CSV format. https://github.com/facebookresearch/qhoptim/releases/download/emptytag/qhoptim_parameter_sweep_data.tar.gz