<<

Stochastic Gradient Hamiltonian Monte Carlo

Tianqi Chen [email protected] Emily B. Fox [email protected] Carlos Guestrin [email protected] MODE Lab, University of Washington, Seattle, WA.

Abstract simple updates to the variables, one simu- lates from a Hamiltonian dynamical system that enables Hamiltonian Monte Carlo (HMC) sampling proposals of distant states. The target distribution is in- methods provide a mechanism for defining dis- variant under these dynamics; in practice, a discretiza- tant proposals with high acceptance probabilities tion of the continuous-time system is needed necessitating in a Metropolis-Hastings framework, enabling a Metropolis-Hastings (MH) correction, though still with more efficient exploration of the state space than high acceptance probability. Based on the attractive proper- standard random-walk proposals. The popularity ties of HMC in terms of rapid exploration of the state space, of such methods has grown significantly in recen- HMC methods have grown in popularity recently (Neal, t years. However, a limitation of HMC methods 2010; Hoffman & Gelman, 2011; Wang et al., 2013). is the required gradient computation for simula- tion of the Hamiltonian dynamical system—such A limitation of HMC, however, is the necessity to com- computation is infeasible in problems involving a pute the gradient of the function in order large sample size or streaming data. Instead, we to simulate the Hamiltonian dynamical system. We are in- must rely on a noisy gradient estimate computed creasingly faced with datasets having millions to billions from a subset of the data. In this paper, we ex- of observations or where data come in as a stream and we plore the properties of such a stochastic gradient need to make inferences online, such as in online advertis- HMC approach. Surprisingly, the natural imple- ing or recommender systems. In these ever-more-common mentation of the stochastic approximation can be scenarios of massive batch or streaming data, such gradi- arbitrarily bad. To address this problem we intro- ent computations are infeasible since they utilize the entire duce a variant that uses second-order Langevin dataset, and thus are not applicable to “big data” problem- dynamics with a friction term that counteracts the s. Recently, in a variety of machine learning algorithms, effects of the noisy gradient, maintaining the de- we have witnessed the many successes of utilizing a noisy sired target distribution as the invariant distribu- estimate of the gradient based on a minibatch of data to tion. Results on simulated data validate our the- scale the algorithms (Robbins & Monro, 1951; Hoffman ory. We also provide an application of our meth- et al., 2013; Welling & Teh, 2011). A majority of these ods to a classification task using neural networks developments have been in optimization-based algorithm- and to online Bayesian matrix factorization. s (Robbins & Monro, 1951; Nemirovski et al., 2009), and a question is whether similar efficiencies can be garnered by sampling-based algorithms that maintain many desir- 1. Introduction able theoretical properties for Bayesian inference. One at- tempt at applying such methods in a sampling context is the Hamiltonian Monte Carlo (HMC) (Duane et al., 1987; recently proposed stochastic gradient Langevin dynamics Neal, 2010) sampling methods provide a powerful Markov (SGLD) (Welling & Teh, 2011; Ahn et al., 2012; Patterson chain Monte Carlo (MCMC) sampling algorithm. The & Teh, 2013). This method builds on first-order Langevin methods define a Hamiltonian function in terms of the tar- dynamics that do not include the crucial momentum term get distribution from which we desire samples—the po- of HMC. tential energy—and a kinetic energy term parameterized by a set of “momentum” auxiliary variables. Based on In this paper, we explore the possibility of marrying the efficiencies in state space exploration of HMC with the Proceedings of the 31 st International Conference on Machine big-data computational efficiencies of stochastic gradients. Learning, Beijing, China, 2014. JMLR: W&CP volume 32. Copy- Such an algorithm would enable a large-scale and online right 2014 by the author(s). Stochastic Gradient Hamiltonian Monte Carlo

Bayesian sampling algorithm with the potential to rapidly Hamiltonian (Hybrid) Monte Carlo (HMC) (Duane et al., explore the posterior. As a first cut, we consider simply 1987; Neal, 2010) provides a method for proposing sam- applying a stochastic gradient modification to HMC and ples of θ in a Metropolis-Hastings (MH) framework that assess the impact of the noisy gradient. We prove that the efficiently explores the state space as compared to stan- noise injected in the system by the stochastic gradient no dard random-walk proposals. These proposals are gener- longer leads to Hamiltonian dynamics with the desired tar- ated from a Hamiltonian system based on introducing a set get distribution as the stationary distribution. As such, even of auxiliary momentum variables, r. That is, to sample before discretizing the dynamical system, we need to cor- from p(θ|D), HMC considers generating samples from a rect for this effect. One can correct for the injected gradi- joint distribution of (θ, r) defined by ent noise through an MH step, though this itself requires  1  costly computations on the entire dataset. In practice, one π(θ, r) ∝ exp −U(θ) − rT M −1r . (3) might propose long simulation runs before an MH correc- 2 tion, but this leads to low acceptance rates due to large de- If we simply discard the resulting r samples, the θ sam- viations in the Hamiltonian from the injected noise. The ples have marginal distribution p(θ|D). Here, M is a mass efficiency of this MH step could potentially be improved matrix, and together with r, defines a kinetic energy term. using the recent results of (Korattikara et al., 2014; Bar- M is often set to the identity matrix, I, but can be used to denet et al., 2014). In this paper, we instead introduce a precondition the sampler when we have more information stochastic gradient HMC method with friction added to the about the target distribution. The Hamiltonian function is momentum update. We assume the injected noise is Gaus- 1 T −1 defined by H(θ, r) = U(θ) + 2 r M r. Intuitively, H sian, appealing to the central limit theorem, and analyze the measures the total energy of a physical system with posi- corresponding dynamics. We show that using such second- tion variables θ and momentum variables r. order Langevin dynamics enables us to maintain the desired target distribution as the stationary distribution. That is, the To propose samples, HMC simulates the Hamiltonian dy- friction counteracts the effects of the injected noise. For namics  dθ = M −1r dt discretized systems, we consider letting the step size tend (4) dr = −∇U(θ) dt. to zero so that an MH step is not needed, giving us a sig- nificant computational advantage. Empirically, we demon- To make Eq. (4) concrete, a common analogy in 2D is as strate that we have good performance even for  set to a follows (Neal, 2010). Imagine a hockey puck sliding over a small, fixed value. The theoretical computation versus ac- frictionless ice surface of varying height. The potential en- curacy tradeoff of this small- approach is provided in the ergy term is based on the height of the surface at the current Supplementary Material. puck position, θ, while the kinetic energy is based on the momentum of the puck, r, and its mass, M. If the surface A number of simulated experiments validate our theoretical is flat (∇U(θ) = 0, ∀θ), the puck moves at a constant ve- results and demonstrate the differences between (i) exact locity. For positive slopes (∇U(θ) > 0), the kinetic energy HMC, (ii) the na¨ıve implementation of stochastic gradient decreases as the potential energy increases until the kinet- HMC (simply replacing the gradient with a stochastic gra- ic energy is 0 (r = 0). The puck then slides back down dient), and (iii) our proposed method incorporating friction. the hill increasing its kinetic energy and decreasing poten- We also compare to the first-order Langevin dynamics of tial energy. Recall that in HMC, the position variables are SGLD. Finally, we apply our proposed methods to a classi- those of direct interest whereas the momentum variables fication task using Bayesian neural networks and to online are artificial constructs (auxiliary variables). Bayesian matrix factorization of a standard movie dataset. Our experimental results demonstrate the effectiveness of Over any interval s, the Hamiltonian dynamics of Eq. (4) the proposed algorithm. defines a mapping from the state at time t to the state at time t + s. Importantly, this mapping is reversible, which 2. Hamiltonian Monte Carlo is important in showing that the dynamics leave π invari- ant. Likewise, the dynamics preserve the total energy, H, Suppose we want to sample from the posterior distribution so proposals are always accepted. In practice, however, we of θ given a set of independent observations x ∈ D: usually cannot simulate exactly from the continuous system of Eq. (4) and instead consider a discretized system. One p(θ|D) ∝ exp(−U(θ)), (1) common approach is the “leapfrog” method, which is out- lined in Alg.1. Because of inaccuracies introduced through where the potential energy function U is given by the discretization, an MH step must be implemented (i.e., the acceptance rate is no longer 1). However, acceptance X U = − log p(x|θ) − log p(θ). (2) rates still tend to be high even for proposals that can be x∈D quite far from their last state. Stochastic Gradient Hamiltonian Monte Carlo

Algorithm 1: Hamiltonian Monte Carlo noisy gradient as Input: Starting position θ(1) and step size  ∇U˜(θ) ≈ ∇U(θ) + N (0,V (θ)). (6) for t = 1, 2 ··· do Resample momentum r Here, V is the covariance of the stochastic gradient noise, r(t) ∼ N (0,M) which can depend on the current model parameters and (t) (t) (θ0, r0) = (θ , r ) sample size. Note that we use an abuse of notation in E- Simulate discretization of Hamiltonian dynamics q. (6) where the addition of N (µ, Σ) denotes the introduc- in Eq. (4): tion of a that is distributed according to  D˜ r0 ← r0 − 2 ∇U(θ0) this multivariate Gaussian. As the size of increases, this for i = 1 to m do Gaussian approximation becomes more accurate. Clearly, −1 θi ← θi−1 + M ri−1 we want minibatches to be small to have our sought-after ri ← ri−1 − ∇U(θi) computational gains. Empirically, in a wide range of set- end tings, simply considering a minibatch size on the order of  rm ← rm − 2 ∇U(θm) hundreds of data points is sufficient for the central limit ˆ (θ, rˆ) = (θm, rm) theorem approximation to be accurate (Ahn et al., 2012). Metropolis-Hastings correction: In our applications of interest, minibatches of this size still u ∼ Uniform[0, 1] represent a significant reduction in the computational cost (t) (t) ρ = eH(θ,ˆ rˆ)−H(θ ,r ) of the gradient. if u < min(1, ρ), then θ(t+1) = θˆ end 3.1. Na¨ıve Stochastic Gradient HMC The most straightforward approach to stochastic gradient HMC is simply to replace ∇U(θ) in Alg.1 by ∇U˜(θ). Re- ferring to Eq. (6), this introduces noise in the momentum There have been many recent developments of HMC to update, which becomes ∆r = −∇U˜(θ) = −∇U(θ) + make the algorithm more flexible and applicable in a va- N (0, 2V ). The resulting discrete time system can be riety of settings. The “No U-Turn” sampler (Hoffman & viewed as an -discretization of the following continuous Gelman, 2011) and the methods proposed by Wang et al. stochastic differential equation: (2013) allow automatic tuning of the step size, , and num- ber of simulation steps, m. Riemann manifold HMC (Giro-  dθ = M −1r dt (7) lami & Calderhead, 2011) makes use of the Riemann ge- dr = −∇U(θ) dt + N (0, 2B(θ)dt). ometry to adapt the mass M, enabling the algorithm to 1 make use of curvature information to perform more effi- Here, B(θ) = 2 V (θ) is the diffusion matrix contributed cient sampling. We attempt to improve HMC in an orthog- by gradient noise. As with the original HMC formulation, onal direction focused on computational complexity, but it is useful to return to a continuous time system in order to these adaptive HMC techniques could potentially be com- derive properties of the approach. To gain some intuition bined with our proposed methods to see further benefits. about this setting, consider the same hockey puck analogy of Sec.2. Here, we can imagine the puck on the same 3. Stochastic Gradient HMC ice surface, but with some random wind blowing as well. This wind may blow the puck further away than expected. In this section, we study the implications of implementing Formally, as given by Corollary 3.1 of Theorem 3.1, when HMC using a stochastic gradient and propose variants on B is nonzero, π(θ, r) of Eq. (3) is no longer invariant under the Hamiltonian dynamics that are more robust to the noise the dynamics described by Eq. (7). introduced by the stochastic gradient estimates. In all s- Theorem 3.1. Let pt(θ, r) be the distribution of (θ, r) at cenarios, instead of directly computing the costly gradient time t with dynamics governed by Eq. (7). Define the ∇U(θ) using Eq. (2), which requires examination of the R entropy of pt as h(pt) = − θ,r f(pt(θ, r))dθdr, where entire dataset D, we consider a noisy estimate based on a f(x) = x ln x. Assume p is a distribution with density ˜ t minibatch D sampled uniformly at random from D: and gradient vanishing at infinity. Furthermore, assume the gradient vanishes faster than 1 . Then, the entropy of ln pt |D| X pt increases over time with rate ∇U˜(θ) = − ∇ log p(x|θ) − ∇ log p(θ), D˜ ⊂ D. ˜ |D| ˜ x∈D ∂th(pt(θ, r)) = (5) Z 00 T We assume that our observations x are independent and, f (pt)(∇rpt(θ, r)) B(θ)∇rpt(θ, r)dθdr. (8) appealing to the central limit theorem, approximate this θ,r Stochastic Gradient Hamiltonian Monte Carlo

Eq. (8) implies that ∂th(pt(θ, r)) ≥ 0 since B(θ) is a pos- rection of future research is to consider using the recent re- itive semi-definite matrix. sults of Korattikara et al.(2014) and Bardenet et al.(2014) that show that it is possible to do MH using a subset of data. Intuitively, Theorem 3.1 is true because the noise-free However, we instead consider in Sec. 3.2 a straightforward Hamiltonian dynamics preserve entropy, while the addi- modification to the Hamiltonian dynamics that alleviates tional noise term strictly increases entropy if we assume the issues of the noise introduced by stochastic gradients. (i) B(θ) is positive definite (a reasonable assumption due In particular, our modification allows us to again achieve to the normal full rank property of Fisher information) and the desired π as the invariant distribution of the continuous (ii) ∇rpt(θ, r) 6= 0 for all t. Then, jointly, the entropy Hamiltonian dynamical system. strictly increases over time. This hints at the fact that the distribution pt tends toward a uniform distribution, which 3.2. Stochastic Gradient HMC with Friction can be very far from the target distribution π. In Sec. 3.1, we showed that HMC with stochastic gradients Corollary 3.1. The distribution π(θ, r) ∝ exp (−H(θ, r)) requires a frequent costly MH correction step, or alterna- is no longer invariant under the dynamics in Eq. (7). tively, long simulation runs with low acceptance probabili- ties. Ideally, instead, we would like to minimize the effect The proofs of Theorem 3.1 and Corollary 3.1 are in the of the injected noise on the dynamics themselves to allevi- Supplementary Material. ate these problems. To this end, we consider a modification Because π is no longer invariant under the dynamics of to Eq. (7) that adds a “friction” term to the momentum up- Eq. (7), we must introduce a correction step even before date: considering errors introduced by the discretization of the  dθ = M −1r dt dynamical system. For the correctness of an MH step (9) dr = −∇U(θ) dt − BM −1rdt + N (0, 2Bdt). (based on the entire dataset), we appeal to the same argu- ments made for the HMC data-splitting technique of Neal Here and throughout the remainder of the paper, we omit (2010). This approach likewise considers minibatches of the dependence of B on θ for simplicity of notation. Let us data and simulating the (continuous) Hamiltonian dynam- again make a hockey analogy. Imagine we are now playing ics on each batch sequentially. Importantly, Neal(2010) street hockey instead of ice hockey, which introduces fric- alludes to the fact that the resulting H from the split-data tion from the asphalt. There is still a random wind blowing, scenario may be far from that of the full-data scenario af- however the friction of the surface prevents the puck from ter simulation, which leads to lower acceptance rates and running far away. That is, the friction term BM −1r help- thereby reduces the apparent computational gains in simu- s decrease the energy H(θ, r), thus reducing the influence lation. Empirically, as we demonstrate in Fig.2, we see that of the noise. This type of dynamical system is commonly even finite-length simulations from the noisy system can referred to as second-order Langevin dynamics in physic- diverge quite substantially from those of the noise-free sys- s (Wang & Uhlenbeck, 1945). Importantly, we note that the tem. Although the minibatch-based HMC technique con- Langevin dynamics used in SGLD (Welling & Teh, 2011) sidered herein is slightly different from that of Neal(2010), are first-order, which can be viewed as a limiting case of the theory we have developed in Theorem 3.1 surrounding our second-order dynamics when the friction term is large. the high-entropy properties of the resulting invariant distri- Further details on this comparison follow at the end of this bution of Eq. (7) provides some intuition for the observed section. deviations in H both in our experiments and those of Neal (2010). Theorem 3.2. π(θ, r) ∝ exp(−H(θ, r)) is the unique sta- tionary distribution of the dynamics described by Eq. (9). The poorly behaved properties of the trajectory of H based on simulations using noisy gradients results in a complex  0 −I   0 0  computation versus efficiency tradeoff. On one hand, it Proof. Let G = , D = , where G is extremely computationally intensive in large datasets to I 0 0 B insert an MH step after just short simulation runs (where is an anti-symmetric matrix, and D is the symmetric (d- deviations in H are less pronounced and acceptance rates iffusion) matrix. Eq. (9) can be written in the following should be reasonable). Each of these MH steps requires a decomposed form (Yin & Ao, 2006; Shi et al., 2012) all costly computation using of the data, thus defeating the       computational gains of considering noisy gradients. On the θ 0 −I ∇U(θ) d = − −1 dt + N (0, 2Ddt) other hand, long simulation runs between MH steps can r IB M r lead to very low acceptance rates. Each rejection corre- = − [D + G] ∇H(θ, r)dt + N (0, 2Ddt). sponds to a wasted (noisy) gradient computation and simu- lation using the proposed variant of Alg.1. One possible di- The distribution evolution under this dynamical system is Stochastic Gradient Hamiltonian Monte Carlo governed by a Fokker-Planck equation Algorithm 2: Stochastic Gradient HMC

T for t = 1, 2 ··· do ∂tpt(θ, r)=∇ {[D+G][pt(θ, r)∇H(θ, r) + ∇pt(θ, r)]}. optionally, resample momentum r as (10) r(t) ∼ N (0,M) See the Supplementary Material for details. We can ver- (t) (t) (θ0, r0) = (θ , r ) ify that π(θ, r) is invariant under Eq. (10) by calculating simulate dynamics in Eq.(13):  −H(θ,r) −H(θ,r) e ∇H(θ, r) + ∇e = 0. Furthermore, due for i = 1 to m do to the existence of diffusion noise, π is the unique station- −1 θi ← θi−1 + tM ri−1 ary distribution of Eq. (10). −1 ri ← ri−1 − t∇U˜(θi) − tCM ri−1 +N (0, 2(C − Bˆ)t) In summary, we have shown that the dynamics given by end (t+1) (t+1) Eq. (9) have a similar invariance property to that of the o- (θ , r ) = (θm, rm), no M-H step riginal Hamiltonian dynamics of Eq. (4), even with noise end present. The key was to introduce a friction term using second-order Langevin dynamics. Our revised momen- tum update can also be viewed as akin to partial momen- 3.3. Stochastic Gradient HMC in Practice tum refreshment (Horowitz, 1991; Neal, 1993), which al- so corresponds to second-order Langevin dynamics. Such In everything we have considered so far, we have assumed partial momentum refreshment was shown to not greatly that we know the noise model B. Clearly, in practice this improve HMC in the case of noise-free gradients (Neal, is not the case. Imagine instead that we simply have an es- 2010). However, as we have demonstrated, the idea is cru- timate Bˆ. As will become clear, it is beneficial to instead cial in our stochastic gradient scenario in order to counter- introduce a user specified friction term C  Bˆ and consid- balance the effect of the noisy gradients. We refer to the er the following dynamics resulting method as stochastic gradient HMC (SGHMC).  dθ = M −1r dt  −1 CONNECTIONTO FIRST-ORDER LANGEVIN DYNAMICS dr = −∇U(θ) dt − CM rdt (13)  +N (0, 2(C − Bˆ)dt) + N (0, 2Bdt) As we previously discussed, the dynamics introduced in E- q. (9) relate to the first-order Langevin dynamics used in S- The resulting SGHMC algorithm is shown in Alg.2. Note GLD (Welling & Teh, 2011). In particular, the dynamics of that the algorithm is purely in terms of user-specified or SGLD can be viewed as second-order Langevin dynamics computable quantities. To understand our choice of dy- with a large friction term. To intuitively demonstrate this namics, we begin with the unrealistic scenario of perfect −1 1 connection, let BM = dt in Eq. (9). Because the fric- estimation of B. tion and momentum noise terms are very large, the momen- Proposition 3.1. If Bˆ = B, then the dynamics of Eq. (13) tum variable r changes much faster than θ. Thus, relative yield the stationary distribution π(θ, r) ∝ e−H(θ,r). to the rapidly changing momentum, θ can be considered as fixed. We can study this case as simply: Proof. The momentum update simplifies to r = −1 dr = −∇U(θ)dt − BM −1rdt + N (0, 2Bdt) (11) −∇U(θ) dt−CM rdt+N (0, 2Cdt), with friction term CM −1 and noise term N (0, 2Cdt). Noting that the proof The fast evolution of r leads to a rapid convergence to of Theorem 3.2 only relied on a matching of noise and fric- the stationary distribution of Eq. (11), which is given by tion, the result follows directly by using C in place of B in N (MB−1∇U(θ),M). Let us now consider a change in θ, Theorem 3.2. −1 −1 1 with r ∼ N (MB ∇U(θ),M). Recalling BM = dt , we have Now consider the benefit of introducing the C terms and revised dynamics in the more realistic scenario of inaccu- dθ = −M −1∇U(θ)dt2 + N (0, 2M −1dt2), (12) rate estimation of B. For example, the simplest choice is Bˆ = 0. Though the true stochastic gradient noise B is 1 which exactly aligns with the dynamics of SGLD where clearly non-zero, as the step size  → 0, B = 2 V goes to 0 M −1 serves as the preconditioning matrix (Welling & Teh, and C dominates. That is, the dynamics are again governed 2011). Intuitively, this means that when the friction is by the controllable injected noise N (0, 2Cdt) and friction −1 ˆ 1 ˆ ˆ large, the dynamics do not depend on the decaying series CM . It is also possible to set B = 2 V , where V is esti- of past gradients represented by dr, reducing to first-order mated using empirical Fisher information as in (Ahn et al., Langevin dynamics. 2012) for SGLD. Stochastic Gradient Hamiltonian Monte Carlo

COMPUTATIONAL COMPLEXITY 0.8 True Distribution 0.7 Standard HMC(with MH) The complexity of Alg.2 depends on the choice of M, C Standard HMC(no MH) ˆ ˜ Naive stochastic gradient HMC(with MH) and B, and the complexity for estimating ∇U(θ)—denoted 0.6 Naive stochastic gradient HMC(no MH) SGHMC as g(|D|, d)—where d is the dimension of the parameter s- 0.5 pace. Assume we allow Bˆ to be an arbitrary d × d pos- 0.4 itive definite matrix. Using empirical Fisher information estimation of Bˆ, the per-iteration complexity of this esti- 0.3 mation step is O(d2|D|˜ ). Then, the time complexity for 0.2 3 the (θ, r) update is O(d ), because the update is dom- 0.1 inated by generating Gaussian noise with a full covari- 0 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 ance matrix. In total, the per-iteration time complexity is θ 2 3 O(d |D|˜ + d + g(|D|˜ , d)). In practice, we restrict all of Figure 1. Empirical distributions associated with various sam- the matrices to be diagonal when d is large, resulting in pling algorithms relative to the true target distribution with time complexity O(d|D|˜ + d + g(|D|˜ , d)). Importantly, we U(θ) = −2θ2 + θ4. We compare the HMC method of Alg.1 note that our SGHMC time complexity is the same as that with and without the MH step to: (i) a naive variant that replaces of SGLD (Welling & Teh, 2011; Ahn et al., 2012) in both the gradient with a stochastic gradient, again with and without an parameter settings. MH correction; (ii) the proposed SGHMC method, which does not use an MH correction. We use ∇U˜(θ) = ∇U(θ) + N (0, 4) In practice, we must assume inaccurate estimation of B. in the stochastic gradient based samplers and  = 0.1 in all cases. For a decaying series of step sizes t, an MH step is not Momentum is resampled every 50 steps in all variants of HMC. required (Welling & Teh, 2011; Ahn et al., 2012)1. Howev- er, as the step size decreases, the efficiency of the sampler gradient method with momentum. We can use the equiv- likewise decreases since proposals are increasingly close alent update rule of Eq. (15) to run SGHMC, and borrow to their initial value. In practice, we may want to tolerate experience from parameter settings of SGD with momen- some errors in the sampling accuracy to gain efficiency. As tum to guide our choices of SGHMC settings. For example, in (Welling & Teh, 2011; Ahn et al., 2012) for SGLD, we we can set α to a fixed small number (e.g., 0.01 or 0.1), s- ˆ ˆ consider using a small, non-zero  leading to some bias. We elect the learning rate η, and then fix β = ηV/2. A more explore an analysis of the errors introduced by such finite- sophisticated strategy involves using momentum schedul- approximations in the Supplementary Material. ing (Sutskever et al., 2013). We elaborate upon how to se- lect these parameters in the Supplementary Material. CONNECTIONTO SGD WITH MOMENTUM Adding a momentum term to stochastic gradient descent 4. Experiments (SGD) is common practice. In concept, there is a clear rela- 4.1. Simulated Scenarios tionship between SGD with momentum and SGHMC, and here we formalize this connection. Letting v = M −1r, To empirically explore the behavior of HMC using exact we first rewrite the update rule in Alg.2 as gradients relative to stochastic gradients, we conduct ex- periments on a simulated setup. As a baseline, we consider  ∆θ = v the standard HMC implementation of Alg.1, both with and  ∆v = −2M −1∇U˜(θ) − M −1Cv (14) without the MH correction. We then compare to HMC with  +N (0, 23M −1(C − Bˆ)M −1). stochastic gradients, replacing ∇U in Alg.1 with ∇U˜, and consider this proposal with and without an MH correction. Define η = 2M −1, α = M −1C, βˆ = M −1Bˆ. The Finally, we compare to our proposed SGHMC, which does update rule becomes not use an MH correction. Fig.1 shows the empirical distri- butions generated by the different sampling algorithms. We  ∆θ = v see that even without an MH correction, both the HMC and (15) ∆v = −η∇U˜(x) − αv + N (0, 2(α − βˆ)η). SGHMC algorithms provide results close to the true distri- bution, implying that any errors from considering non-zero Comparing to an SGD with momentum method, it is clear  are negligible. On the other hand, the results of na¨ıve s- from Eq. (15) that η corresponds to the learning rate and tochastic gradient HMC diverge significantly from the truth 1−α the momentum term. When the noise is removed (via unless an MH correction is added. These findings validate ˆ C = B = 0), SGHMC naturally reduces to a stochastic our theoretical results; that is, both standard HMC and S- 1We note that, just as in SGLD, an MH correction is not even GHMC maintain π as the invariant distribution as  → 0 possible because we cannot compute the probability of the reverse whereas na¨ıve stochastic gradient HMC does not, though dynamics. this can be corrected for using a (costly) MH step. Stochastic Gradient Hamiltonian Monte Carlo

8 property. Fig.3 compares SGHMC and SGLD (Welling Noisy Hamiltonian dynamics Noisy Hamiltonian dynamics(resample r each 50 steps) & Teh, 2011) when sampling from a bivariate Gaussian 6 Noisy Hamiltonian dynamics with friction Hamiltonian dynamics with positive correlation. For each method, we examine 4 five different settings of the initial step size on a linear- 2 ly decreasing scale and generate ten million samples. For

r 0 each of these sets of samples (one set per step-size setting), we calculate the autocorrelation time2 of the samples and −2 the average absolute error of the resulting sample covari- −4 ance. Fig.3(a) shows the autocorrelation versus estima- −6 tion error for the five settings. As we decrease the step-

−8 size, SGLD has reasonably low estimation error but high −8 −6 −4 −2 0 2 4 6 8 θ autocorrelation time indicating an inefficient sampler. In Figure 2. Points (θ,r) simulated from discretizations of various contrast, SGHMC achieves even lower estimation error at 1 2 Hamiltonian dynamics over 15000 steps using U(θ) = 2 θ and very low autocorrelation times, from which we conclude  = 0.1. For the noisy scenarios, we replace the gradient by that the sampler is indeed efficiently exploring the distribu- ∇U˜(θ) = θ + N (0, 4). We see that noisy Hamiltonian dynam- tion. Fig.3(b) shows the first 50 samples generated by the ics lead to diverging trajectories when friction is not introduced. two samplers. We see that SGLD’s random-walk behavior Resampling r helps control divergence, but the associated HMC makes it challenging to explore the tails of the distribution. stationary distribution is not correct, as illustrated in Fig.1. The momentum variable associated with SGHMC instead

0.45 3 drives the sampler to move along the distribution contours. SGLD SGLD 0.4 SGHMC SGHMC 2 0.35 4.2. Bayesian Neural Networks for Classification 0.3 1 0.25 y We also test our method on a handwritten digits classifica- 0.2 0 3 0.15 tion task using the MNIST dataset . The dataset consists 0.1 −1 of 60,000 training instances and 10,000 test instances. We 0.05 randomly split a validation set containing 10,000 instances 0 −2 Average Absolute Error of Sample Covariance 0 50 100 150 200 −2 −1 0 1 2 3 Autocorrelation Time x from the training data in order to select training parame- Figure 3. Contrasting sampling of a bivariate Gaussian with cor- ters, and use the remaining 50,000 instances for training. 1 T −1 For classification, we consider a two layer Bayesian neu- relation using SGHMC versus SGLD. Here, U(θ) = 2 θ Σ θ, −1 ral network with 100 hidden variables using a sigmoid unit ∇U˜(θ) = Σ θ + N (0,I) with Σ11 = Σ22 = 1 and correlation ρ = Σ12 = 0.9. Left: Mean absolute error of the covariance and an output layer using softmax. We tested four meth- estimation using ten million samples versus autocorrelation time ods: SGD, SGD with momentum, SGLD and SGHMC. of the samples as a function of 5 step size settings. Right: First For the optimization-based methods, we use the validation 50 samples of SGHMC and SGLD. set to select the optimal regularizer λ of network weights4. For the sampling-based methods, we take a fully Bayesian We also consider simply simulating from the discretized approach and place a weakly informative gamma prior on Hamiltonian dynamical systems associated with the vari- each layer’s weight regularizer λ. The sampling procedure ous samplers compared. In Fig.2, we compare the result- is carried out by running SGHMC and SGLD using mini- ing trajectories and see that the path of (θ, r) from the noisy batches of 500 training instances, then resampling hyperpa- system without friction diverges significantly. The modifi- rameters after an entire pass over the training set. We run cation of the dynamical system by adding friction (corre- the samplers for 800 iterations (each over the entire training sponding to SGHMC) corrects this behavior. We can al- dataset) and discard the initial 50 samples as burn-in. so correct for this divergence through periodic resampling The test error as a function of MCMC or optimization iter- of the momentum, though as we saw in Fig.1, the cor- ation (after burn-in) is reported for each of these methods responding MCMC algorithm (“Naive stochastic gradient in Fig.4. From the results, we see that SGD with mo- HMC (no MH)”) does not yield the correct target distribu- mentum converges faster than SGD. SGHMC also has an tion. These results confirm the importance of the friction advantage over SGLD, converging to a low test error much term in maintaining a well-behaved Hamiltonian and lead- more rapidly. In terms of runtime, in this case the gradien- ing to the correct stationary distribution. 2 P∞ Autocorrelation time is defined as 1 + s=1 ρs, where ρs is It is known that a benefit of HMC over many other MCM- the autocorrelation at lag s. C algorithms is the efficiency in sampling from correlated 3http://yann.lecun.com/exdb/mnist/ distributions (Neal, 2010)—this is where the introduction 4We also tried MAP inference for selecting λ in the of the momentum variable shines. SGHMC inherits this optimization-based method, but found similar performance. Stochastic Gradient Hamiltonian Monte Carlo

0.05 Table 1. Predictive RMSE estimated using 5-fold cross validation SGD on the Movielens dataset for various approaches of inferring pa- 0.045 SGD with momentum SGLD rameters of a Bayesian probabilistic matrix factorization model. 0.04 SGHMC

0.035 METHOD RMSE

0.03 test error SGD 0.8538 ± 0.0009 SGD WITHMOMENTUM 0.8539 ± 0.0009 0.025 SGLD 0.8412 ± 0.0009 0.02 SGHMC 0.8411 ± 0.0011

0.015 0 200 400 600 800 evaluate the performance of the different methods. iteration Figure 4. Convergence of test error on the MNIST dataset using The results are shown in Table1. Both SGHMC and S- SGD, SGD with momentum, SGLD, and SGHMC to infer model GLD give better prediction results than optimization-based parameters of a Bayesian neural net. methods. In this experiment, the results for SGLD and S- GHMC are very similar. We also observed that the per- t computation used in backpropagation dominates so both iteration running time of both methods are comparable. As have the same computational cost. The final results of the such, the experiment suggests that SGHMC is an effective sampling based methods are better than optimization-based candidate for online Bayesian PMF. methods, showing an advantage to Bayesian inference in this setting, thus validating the need for scalable and effi- cient Bayesian inference algorithms such as SGHMC. 5. Conclusion Moving between modes of a distribution is one of the 4.3. Online Bayesian Probabilistic Matrix key challenges for MCMC-based inference algorithms. To Factorization for Movie Recommendations address this problem in the large-scale or online setting, we proposed SGHMC, an efficient method for generat- Collaborative filtering is an important problem in web ap- ing high-quality, “distant” steps in such sampling meth- plications. The task is to predict a user’s preference over ods. Our approach builds on the fundamental framework a set of items (e.g., movies, music) and produce rec- of HMC, but using stochastic estimates of the gradient to ommendations. Probabilistic matrix factorization (PM- avoid the costly full gradient computation. Surprisingly, F) (Salakhutdinov & Mnih, 2008b) has proven effective for we discovered that the natural way to incorporate stochas- this task. Due to the sparsity in the ratings matrix (user- tic gradient estimates into HMC can lead to divergence and s versus items) in recommender systems, over-fitting is a poor behavior both in theory and in practice. To address severe issue with Bayesian approaches providing a natural this challenge, we introduced second-order Langevin dy- solution (Salakhutdinov & Mnih, 2008a). namics with a friction term that counteracts the effects of We conduct an experiment in online Bayesian PMF on the the noisy gradient, maintaining the desired target distribu- Movielens dataset ml-1M5. The dataset contains about 1 tion as the invariant distribution of the continuous system. million ratings of 3,952 movies by 6,040 users. The num- Our empirical results, both in a simulated experiment and ber of latent dimensions is set to 20. In comparing our on real data, validate our theory and demonstrate the practi- stochastic-gradient-based approaches, we use minibatches cal value of introducing this simple modification. A natural of 4,000 ratings to update the user and item latent matri- next step is to explore combining adaptive HMC techniques ces. We choose a significantly larger minibatch size in this with SGHMC. More broadly, we believe that the unifi- application than that of the neural net because of the dra- cation of efficient optimization and sampling techniques, matically larger parameter space associated with the PMF such as those described herein, will enable a significant s- model. For the optimization-based approaches, the hyper- caling of Bayesian methods. parameters are set using cross validation (again, we did not see a performance difference from considering MAP esti- Acknowledgements mation). For the sampling-based approaches, the hyperpa- This work was supported in part by the TerraSwarm Research rameters are updated using a Gibbs step after every 2, 000 Center sponsored by MARCO and DARPA, ONR Grant N00014- steps of sampling model parameters. We run the sampler to 10-1-0746, DARPA Grant FA9550-12-1-0406 negotiated by generate 2,000,000 samples, with the first 100,000 samples AFOSR, NSF IIS-1258741 and Intel ISTC Big Data. We also discarded as burn-in. We use five-fold cross validation to appreciate the discussions with Mark Girolami, Nick Foti, Ping 5http://grouplens.org/datasets/movielens/ Ao and Hong Qian. Stochastic Gradient Hamiltonian Monte Carlo

References Robbins, H. and Monro, S. A stochastic approximation method. The Annals of Mathematical Statistics, 22(3): Ahn, S., Korattikara, A., and Welling, M. Bayesian pos- 400–407, 09 1951. terior sampling via stochastic gradient Fisher scoring. In Proceedings of the 29th International Conference Salakhutdinov, R. and Mnih, A. Bayesian probabilistic on Machine Learning (ICML’12), pp. 1591–1598, July matrix factorization using Monte Carlo. 2012. In Proceedings of the 25th International Conference on Machine Learning (ICML’08) Bardenet, R., Doucet, A., and Holmes, C. Towards scaling , pp. 880–887, 2008a. up : An adaptive subsampling Salakhutdinov, R. and Mnih, A. Probabilistic matrix factor- approach. In Proceedings of the 30th International Con- ization. In Advances in Neural Information Processing ference on Machine Learning (ICML’14), volume 32, p- Systems 20 (NIPS’08), pp. 1257–1264, 2008b. p. 405–413, February 2014. Shi, J., Chen, T., Yuan, R., Yuan, B., and Ao, P. Relation of Duane, S., Kennedy, A.D., Pendleton, B.J., and Roweth, a new interpretation of stochastic differential equations D. Hybrid Monte Carlo. Physics Letters B, 195(2):216 to Ito process. Journal of Statistical Physics, 148(3): – 222, 1987. 579–590, 2012. Girolami, M. and Calderhead, B. Riemann manifold Sutskever, I., Martens, J., Dahl, G. E., and Hinton, G. E. On Langevin and Hamiltonian Monte Carlo methods. Jour- the importance of initialization and momentum in deep nal of the Royal Statistical Society Series B, 73(2):123– learning. In Proceedings of the 30th International Con- 214, 03 2011. ference on Machine Learning (ICML’13), volume 28, p- Hoffman, M.D. and Gelman, A. The No-U-Turn sampler: p. 1139–1147, May 2013. Adaptively setting path lengths in Hamiltonian Monte Wang, M.C. and Uhlenbeck, G.E. On the Theory of the Carlo. arXiv, 1111.4246, 2011. Brownian Motion II. Reviews of Modern Physics, 17(2- Hoffman, M.D., Blei, D. M., Wang, C., and Paisley, J. 3):323, 1945. Stochastic variational inference. Journal of Maching Learning Research, 14(1):1303–1347, May 2013. Wang, Z., Mohamed, S., and Nando, D. Adaptive Hamil- tonian and Riemann manifold Monte Carlo. In Proceed- Horowitz, A.M. A generalized guided Monte Carlo algo- ings of the 30th International Conference on Machine rithm. Physics Letters B, 268(2):247 – 252, 1991. Learning (ICML’13), volume 28, pp. 1462–1470, May 2013. Korattikara, A., Chen, Y., and Welling, M. Austerity in MCMC land: Cutting the Metropolis-Hastings budget. Welling, M. and Teh, Y.W. Bayesian learning via stochastic In Proceedings of the 30th International Conference on gradient Langevin dynamics. In Proceedings of the 28th Machine Learning (ICML’14), volume 32, pp. 181–189, International Conference on Machine Learning (ICM- February 2014. L’11), pp. 681–688, June 2011.

Levin, D.A., Peres, Y., and Wilmer, E.L. Markov Chain- Yin, L. and Ao, P. Existence and construction of dynamical s and Mixing Times. American Mathematical Society, potential in nonequilibrium processes without detailed 2008. balance. Journal of Physics A: Mathematical and Gen- Neal, R.M. Bayesian learning via stochastic dynamics. In eral, 39(27):8593, 2006. Advances in Neural Information Processing Systems 5 (NIPS’93), pp. 475–482, 1993. Neal, R.M. MCMC using Hamiltonian dynamics. Hand- book of Markov Chain Monte Carlo, 54:113–162, 2010. Nemirovski, A., Juditsky, A., Lan, G., and Shapiro, A. Robust stochastic approximation approach to stochastic programming. SIAM Journal on Optimization, 19(4): 1574–1609, January 2009. Patterson, S. and Teh, Y.W. Stochastic gradient Rieman- nian Langevin dynamics on the probability simplex. In Advances in Neural Information Processing Systems 26 (NIPS’13), pp. 3102–3110. 2013.