Optimization and Gradient Descent on Riemannian Manifolds
Adapt gradient descent to curved spaces: the metric, the geodesic step, retractions and the natural gradient, with proofs and Python checks.
Learning goals: compute a gradient for a metric; run Riemannian gradient descent and choose its step; use a retraction; relate the natural gradient to the Fisher metric.
Context and objectives
Optimizing when the unknown is not in a vector space
Gradient descent is the workhorse of numerical optimization and of machine learning. It is written for an unknown $x\in\mathbb R^n$: $x_{t+1}=x_t-\alpha\nabla f(x_t)$. Two ingredients make it work: the gradient is the direction of steepest ascent, and $x-\alpha\nabla f$ is a legitimate point. If $x$ lives on a sphere (a direction, an eigenvector), on a rotation group (an orientation), or in a family of probability distributions, neither is true as written: the subtraction leaves the set, and the notion of steepest depends on how we measure lengths.
This course adapts both ingredients, using the tools of Riemannian Geometry: the gradient is computed with the metric, and one moves along geodesics, or along cheaper curves called retractions. The last part shows that the natural gradient of machine learning is nothing else than gradient descent for the Fisher metric.

Objectives to carry out
- Measure the convergence rate of gradient descent on a quadratic function and compare with the theory (Part 1).
- Show that the direction of steepest descent depends on the metric and equals $G^{-1}d^{\top}$ (Part 1).
- Minimize the Rayleigh quotient on the sphere with Riemannian gradient descent, and study the step size (Part 2).
- Replace the exponential map by a retraction and verify numerically that the two agree to third order (Part 3).
- Compute a Fisher metric, compare gradient and natural gradient on a maximum-likelihood problem, and relate the Fisher metric to the KL divergence (Part 4).
- Deliver a report with numbers, proofs and limits (Part 5).
Each part has a short course with proofs and small exercises with a light Python starting code (TO DO lines); the correction, commented, is folded after each exercise.
How to work: environment
Install numpy matplotlib (Python 3.9 or later; checked with Python 3.12 and NumPy 2). Run the blocks in order in one session. The proofs of Parts 1 and 3 are short: write them yourself before reading.
import numpy as npimport matplotlib.pyplot as pltrng = np.random.default_rng(0)np.set_printoptions(precision=6, suppress=True)def unit(v): return v / np.linalg.norm(v)def project(x, v): """Orthogonal projection onto the tangent space of the unit sphere at x.""" return v - (x @ v) * xdef exp_map(x, v): """Exponential map of the unit sphere: the great circle through x with initial velocity v.""" nv = np.linalg.norm(v) return x if nv < 1e-14 else np.cos(nv) * x + np.sin(nv) * v / nv
Part 1 · Gradient descent and the role of the metric
Gradient descent and its rate on a quadratic
For $f:\mathbb R^n\to\mathbb R$, gradient descent with a step $\alpha>0$ is $x_{t+1}=x_t-\alpha\nabla f(x_t)$. The justification is that $-\nabla f$ is the steepest descent direction (Proposition of the previous course with $G=I$). On a quadratic $f(x)=\tfrac12x^{\top}Ax$ with $A$ symmetric positive definite with eigenvalues $0<\lambda_{\min}\le\dots\le\lambda_{\max}$, the iteration is linear: $x_{t+1}=(I-\alpha A)x_t$.
$|x_t|\le\rho(\alpha)^t|x_0|$ with $\rho(\alpha)=\max_i|1-\alpha\lambda_i|$, and $\rho$ is minimal for $\alpha^{\star}=2/(\lambda_{\min}+\lambda_{\max})$, where $\rho^{\star}=\dfrac{\kappa-1}{\kappa+1}$ and $\kappa=\lambda_{\max}/\lambda_{\min}$.
Proof
In an orthonormal eigenbasis of $A$, each coordinate is multiplied by $1-\alpha\lambda_i$ at each step, so the largest factor in absolute value controls the decay. The function $\alpha\mapsto\max(|1-\alpha\lambda_{\min}|,|1-\alpha\lambda_{\max}|)$ is minimal when $1-\alpha\lambda_{\min}=-(1-\alpha\lambda_{\max})$, i.e. $\alpha=2/(\lambda_{\min}+\lambda_{\max})$, which gives $(\lambda_{\max}-\lambda_{\min})/(\lambda_{\max}+\lambda_{\min})$. $\square$
The rate degrades with the condition number $\kappa$: a long narrow valley is slow for gradient descent, and the notion of “steepest” is the culprit, as the next paragraph explains.
Exercise 1.1 · measure the rate
- Write the gradient descent loop and store all iterates.
- For $A=\operatorname{diag}(1,10)$ and three steps, measure the contraction factor per iteration over the last 20 iterations.
- Compare with $\max_i|1-\alpha\lambda_i|$ and with the best possible rate $(\kappa-1)/(\kappa+1)$.
def gradient_descent(grad, x0, step, n_iter): xs = [x0] for _ in range(n_iter): ... # TO DO: move against the gradient: x <- x - alpha grad f(x) return np.array(xs)kappa = 10.0A = np.diag([1.0, kappa]) # f(x) = 1/2 x^T A x, condition number kappagrad = lambda x: A @ x # its gradientx0 = np.array([1.0, 1.0])for step in [0.05, 0.1, 2 / (1 + kappa)]: xs = gradient_descent(grad, x0, step, 60) norms = np.linalg.norm(xs, axis=1) rate = ... # TO DO: measured contraction factor per iteration (last 20 steps) theory = max(abs(1 - step * 1), abs(1 - step * kappa)) # largest |1 - alpha lambda| over the eigenvalues print(f"alpha = {step:.3f}: measured rate {rate:.4f}, theory max|1 - alpha*lambda| = {theory:.4f}")print("best possible rate (kappa - 1)/(kappa + 1) =", (kappa - 1) / (kappa + 1))
Show the correction
def gradient_descent(grad, x0, step, n_iter): xs = [x0] for _ in range(n_iter): xs.append(xs[-1] - step * grad(xs[-1])) # move against the gradient: x <- x - alpha grad f(x) return np.array(xs)kappa = 10.0A = np.diag([1.0, kappa]) # f(x) = 1/2 x^T A x, condition number kappagrad = lambda x: A @ x # its gradientx0 = np.array([1.0, 1.0])for step in [0.05, 0.1, 2 / (1 + kappa)]: xs = gradient_descent(grad, x0, step, 60) norms = np.linalg.norm(xs, axis=1) rate = (norms[60] / norms[40]) ** (1 / 20) # measured contraction factor per iteration (last 20 steps) theory = max(abs(1 - step * 1), abs(1 - step * kappa)) # largest |1 - alpha lambda| over the eigenvalues print(f"alpha = {step:.3f}: measured rate {rate:.4f}, theory max|1 - alpha*lambda| = {theory:.4f}")print("best possible rate (kappa - 1)/(kappa + 1) =", (kappa - 1) / (kappa + 1))
The measured rates $0.9500,\ 0.9000,\ 0.8182$ match $\max_i|1-\alpha\lambda_i|$ to four digits, and the best step reaches $(\kappa-1)/(\kappa+1)=9/11=0.8182$. Reducing the error by $10^{6}$ then takes about 70 iterations; with $\kappa=1000$ it would take about 7,000.
The gradient depends on the metric
For a metric $G$ (a symmetric positive definite matrix) and a differential $d$, the steepest ascent direction among the vectors of $G$-norm 1 is $G^{-1}d^{\top}/|G^{-1}d^{\top}|_G$, and the maximum of $d\,v$ is $|G^{-1}d^{\top}|_G$.
Proof
Put $w=G^{1/2}v$: then $|v|_G=|w|$ and $d\,v=(G^{-1/2}d^{\top})\cdot w$. By Cauchy–Schwarz this is largest for $w$ parallel to $G^{-1/2}d^{\top}$, i.e. $v=G^{-1/2}w\parallel G^{-1}d^{\top}$, and the maximum is $|G^{-1/2}d^{\top}|=\sqrt{d\,G^{-1}d^{\top}}=|G^{-1}d^{\top}|_G$. $\square$
So changing the metric changes the descent direction. A good metric, one that “flattens” the valleys of $f$, makes gradient descent much faster: this is the idea behind preconditioning, Newton’s method (metric = Hessian) and the natural gradient of Part 4.
Exercise 1.2 · steepest descent for a metric
- Draw a random symmetric positive definite matrix $G$ and a random differential $d$.
- Compute the gradient for the metric $G$ and normalize it in the $G$-norm.
- Compare with a brute-force search over 200,000 random vectors of $G$-norm 1.
def random_spd(n): B = rng.normal(size=(n, n)) return B @ B.T + n * np.eye(n)n = 4G = random_spd(n) # a metric (symmetric positive definite matrix)d = rng.normal(size=n) # the differential df at a point (a row of partial derivatives)grad_euclid = d # Euclidean gradient: metric = identitygrad_metric = ... # TO DO: gradient for the metric G: solve G h = ddef best_direction(G, d, n_samples=200000): """Brute-force search of the unit vector (for G) that maximizes the directional derivative d . v.""" V = rng.normal(size=(n_samples, len(d))) V /= np.sqrt(np.einsum("ni,ij,nj->n", V, G, V))[:, None] # unit vectors for the norm |v|_G = sqrt(v^T G v) k = np.argmax(V @ d) return V[k], (V @ d)[k]v, val = best_direction(G, d)h = ... # TO DO: the claim: the best direction is h / |h|_Gprint("brute force best d.v :", val)print("d . (h / |h|_G) :", d @ h, "| |h|_G =", np.sqrt(grad_metric @ G @ grad_metric))print("angle between the two directions (deg):", np.degrees(np.arccos(np.clip(unit(v) @ unit(h), -1, 1))))
Show the correction
def random_spd(n): B = rng.normal(size=(n, n)) return B @ B.T + n * np.eye(n)n = 4G = random_spd(n) # a metric (symmetric positive definite matrix)d = rng.normal(size=n) # the differential df at a point (a row of partial derivatives)grad_euclid = d # Euclidean gradient: metric = identitygrad_metric = np.linalg.solve(G, d) # gradient for the metric G: solve G h = ddef best_direction(G, d, n_samples=200000): """Brute-force search of the unit vector (for G) that maximizes the directional derivative d . v.""" V = rng.normal(size=(n_samples, len(d))) V /= np.sqrt(np.einsum("ni,ij,nj->n", V, G, V))[:, None] # unit vectors for the norm |v|_G = sqrt(v^T G v) k = np.argmax(V @ d) return V[k], (V @ d)[k]v, val = best_direction(G, d)h = grad_metric / np.sqrt(grad_metric @ G @ grad_metric) # the claim: the best direction is h / |h|_Gprint("brute force best d.v :", val)print("d . (h / |h|_G) :", d @ h, "| |h|_G =", np.sqrt(grad_metric @ G @ grad_metric))print("angle between the two directions (deg):", np.degrees(np.arccos(np.clip(unit(v) @ unit(h), -1, 1))))
The best sampled direction is at $1.6^{\circ}$ from $G^{-1}d^{\top}$ and its value is within $0.03\%$ of the maximum $|G^{-1}d^{\top}|_G$; with more samples the gap shrinks. The Euclidean gradient $d^{\top}$ is not the steepest direction for $G$.
Part 2 · Gradient descent on a manifold
Riemannian gradient descent
On a Riemannian manifold $(\mathcal M,g)$, we replace the two ingredients of gradient descent:
- the gradient by the Riemannian gradient $\operatorname{grad}f(x)\in T_x\mathcal M$ (steepest direction for $g$);
- the straight line by the geodesic.
Example: the Rayleigh quotient. For $A$ symmetric, minimize $f(x)=x^{\top}Ax$ on the unit sphere. The Euclidean gradient is $2Ax$ and the Riemannian one is $P_x(2Ax)=2(Ax-(x^{\top}Ax)\,x)$.
$x$ is a critical point of $f$ on the sphere if and only if $x$ is an eigenvector of $A$ ($Ax=f(x)\,x$); the minimum of $f$ is $\lambda_{\min}(A)$, attained at the corresponding eigenvectors.
Proof
$\operatorname{grad}f(x)=0$ means $Ax-(x^{\top}Ax)x=0$. Conversely if $Ax=\lambda x$ then $x^{\top}Ax=\lambda$ and the gradient vanishes. For any unit $x=\sum_ic_iu_i$ in an eigenbasis, $f(x)=\sum_ic_i^2\lambda_i\ge\lambda_{\min}\sum c_i^2=\lambda_{\min}$. $\square$
The algorithm is therefore an eigenvalue solver, and the geometry is exactly that of the sphere. The step size must satisfy a stability condition: at the minimizer the Riemannian Hessian has eigenvalues $2(\lambda_i-\lambda_{\min})$, so a step above $1/(\lambda_{\max}-\lambda_{\min})$ makes the iteration oscillate, by analogy with the quadratic of Part 1.
Exercise 2.1 · minimize the Rayleigh quotient
- Write the Riemannian gradient on the sphere and one step with the exponential map.
- Use a step of $0.5/(\lambda_{\max}-\lambda_{\min})$ and 200 iterations from a random point.
- Check that the final value is $\lambda_{\min}$ and that the final point is an eigenvector.
n = 6Q, _ = np.linalg.qr(rng.normal(size=(n, n))) # a random orthogonal matrixA = Q @ np.diag([-3.0, -1.5, 0.0, 1.0, 2.0, 3.5]) @ Q.T # a symmetric matrix with known eigenvaluesf = lambda x: x @ A @ x # Rayleigh quotient on the unit sphereegrad = lambda x: 2 * A @ x # Euclidean gradientdef rgrad(x): return ... # TO DO: Riemannian gradient on the spheredef riemannian_gd(x0, step, n_iter): x, hist = x0, [] for _ in range(n_iter): g = rgrad(x) hist.append((f(x), np.linalg.norm(g))) x = ... # TO DO: move along the geodesic in the direction -grad f return x, np.array(hist)lam = np.linalg.eigvalsh(A)step = 0.5 / (lam[-1] - lam[0]) # the Hessian of f has eigenvalues up to 2 (lam_max - lam_min): we need a step below 1 / (lam_max - lam_min)x, hist = riemannian_gd(unit(rng.normal(size=n)), step, 200)print("f(x_final) =", f(x), "| smallest eigenvalue =", lam[0])print("|grad f(x_final)| =", hist[-1, 1])print("x_final is an eigenvector: |Ax - f(x)x| =", np.linalg.norm(A @ x - f(x) * x))
Show the correction
n = 6Q, _ = np.linalg.qr(rng.normal(size=(n, n))) # a random orthogonal matrixA = Q @ np.diag([-3.0, -1.5, 0.0, 1.0, 2.0, 3.5]) @ Q.T # a symmetric matrix with known eigenvaluesf = lambda x: x @ A @ x # Rayleigh quotient on the unit sphereegrad = lambda x: 2 * A @ x # Euclidean gradientdef rgrad(x): return project(x, egrad(x)) # Riemannian gradient on the spheredef riemannian_gd(x0, step, n_iter): x, hist = x0, [] for _ in range(n_iter): g = rgrad(x) hist.append((f(x), np.linalg.norm(g))) x = exp_map(x, -step * g) # move along the geodesic in the direction -grad f return x, np.array(hist)lam = np.linalg.eigvalsh(A)step = 0.5 / (lam[-1] - lam[0]) # the Hessian of f has eigenvalues up to 2 (lam_max - lam_min): we need a step below 1 / (lam_max - lam_min)x, hist = riemannian_gd(unit(rng.normal(size=n)), step, 200)print("f(x_final) =", f(x), "| smallest eigenvalue =", lam[0])print("|grad f(x_final)| =", hist[-1, 1])print("x_final is an eigenvector: |Ax - f(x)x| =", np.linalg.norm(A @ x - f(x) * x))
After 200 iterations the value is $-3.0000000$, equal to the smallest eigenvalue, the gradient is of order $10^{-13}$ and $|Ax-f(x)x|\approx5\cdot10^{-14}$: the iterate is an eigenvector to machine precision. The convergence is linear, with a rate set by the gap between the two smallest eigenvalues.
Exercise 2.2 · the step size
- Run the algorithm for the steps $0.1/s$, $0.5/s$ and $1.5/s$, with $s=\lambda_{\max}-\lambda_{\min}$.
- Record the error $f(x_t)-\lambda_{\min}$ and the first iteration where it is below $10^{-6}$.
- Plot the three curves in logarithmic scale and explain what you see.
errors = {}for name, step in [("small step", 0.1 / (lam[-1] - lam[0])), ("good step", 0.5 / (lam[-1] - lam[0])), ("too large step", 1.5 / (lam[-1] - lam[0]))]: x0 = unit(np.random.default_rng(1).normal(size=n)) _, hist = riemannian_gd(x0, step, 200) errors[name] = ... # TO DO: the error f(x_t) - lambda_min along the iterationsfor name, e in errors.items(): first = int(np.argmax(e < 1e-6)) if (e < 1e-6).any() else None print(f"{name:11s}: error after 200 iterations {e[-1]:.2e}; first iteration below 1e-6: {first}")for name, e in errors.items(): plt.semilogy(np.maximum(e, 1e-16), label=name)plt.xlabel("iteration"); plt.ylabel("f(x_t) - lambda_min"); plt.legend(); plt.show()
Show the correction
errors = {}for name, step in [("small step", 0.1 / (lam[-1] - lam[0])), ("good step", 0.5 / (lam[-1] - lam[0])), ("too large step", 1.5 / (lam[-1] - lam[0]))]: x0 = unit(np.random.default_rng(1).normal(size=n)) _, hist = riemannian_gd(x0, step, 200) errors[name] = hist[:, 0] - lam[0] # the error f(x_t) - lambda_min along the iterationsfor name, e in errors.items(): first = int(np.argmax(e < 1e-6)) if (e < 1e-6).any() else None print(f"{name:11s}: error after 200 iterations {e[-1]:.2e}; first iteration below 1e-6: {first}")for name, e in errors.items(): plt.semilogy(np.maximum(e, 1e-16), label=name)plt.xlabel("iteration"); plt.ylabel("f(x_t) - lambda_min"); plt.legend(); plt.show()
The step $0.1/s$ needs 143 iterations to reach $10^{-6}$, the step $0.5/s$ only 27, and the step $1.5/s$ never converges (its error stays of order 3): it is beyond the stability limit of the Hessian, so the iterates oscillate across the valley. Too small is slow, too large is unstable; the best value is a fraction of $1/s$.
Part 3 · Retractions: cheaper ways to move
Retractions: approximate the exponential map
The exponential map of the sphere costs a cosine and a sine, but on other manifolds (matrices of fixed rank, the Stiefel manifold, a general metric) it is expensive or unknown. We only need a map that moves in the right direction. A retraction is a smooth map $R_x:T_x\mathcal M\to\mathcal M$ with $R_x(0)=x$ and $\dfrac d{dt}R_x(tv)\big|_{t=0}=v$. The exponential map is one; on the sphere another one is
\[R_x(v)=\frac{x+v}{|x+v|}:\]leave the tangent plane in a straight line, then come back to the sphere radially. Riemannian gradient descent with a retraction, $x_{t+1}=R_{x_t}(-\alpha\operatorname{grad}f(x_t))$, keeps the convergence guarantees of the exponential version, because the two maps share their first-order behaviour.
For the sphere, $|R_x(v)-\exp_x(v)|=\tfrac13|v|^3+O(|v|^5)$ (second-order agreement of the paths, error of order 3).
Proof
Let $\varepsilon=|v|$ and write $\hat v=v/\varepsilon$, a unit vector orthogonal to $x$. Then $\exp_x(v)=\cos\varepsilon\,x+\sin\varepsilon\,\hat v=(1-\tfrac{\varepsilon^2}2)x+(\varepsilon-\tfrac{\varepsilon^3}6)\hat v+O(\varepsilon^4)$, and $R_x(v)=(x+\varepsilon\hat v)/\sqrt{1+\varepsilon^2}=(1-\tfrac{\varepsilon^2}2)x+(\varepsilon-\tfrac{\varepsilon^3}2)\hat v+O(\varepsilon^4)$. The difference is $(-\tfrac{\varepsilon^3}2+\tfrac{\varepsilon^3}6)\hat v=-\tfrac{\varepsilon^3}3\hat v$ plus terms of order $\varepsilon^4$. $\square$
Exercise 3.1 · check the order of the approximation
- Write the retraction $R_x(v)=(x+v)/|x+v|$ and check $R_x(0)=x$ and the first-order condition.
- For $|v|=0.4,\ 0.2,\ 0.1,\ 0.05,\ 0.025$ compute the distance between $R_x(v)$ and $\exp_x(v)$.
- Estimate the order as the slope of $\log(\text{error})$ against $\log|v|$.
def retract(x, v): return ... # TO DO: normalize x + vx = unit(rng.normal(size=5)); w = unit(project(x, rng.normal(size=5)))print("R_x(0) = x:", np.allclose(retract(x, 0 * w), x))h = 1e-6print("first order: dR_x(tw)/dt at 0 = w:", np.allclose((retract(x, h * w) - retract(x, -h * w)) / (2 * h), w, atol=1e-6))eps = np.array([0.4, 0.2, 0.1, 0.05, 0.025])err = ... # TO DO: distance between the retraction and the exponential maporder = np.diff(np.log(err)) / np.diff(np.log(eps)) # slope of log(error) against log(eps)print("errors:", err)print("observed orders:", order, "(expected 3)")
Show the correction
def retract(x, v): # The retraction R_x(v) = (x + v) / |x + v|: leave the tangent plane in a straight line, then come back to the sphere radially. return (x + v) / np.linalg.norm(x + v) # normalize x + vx = unit(rng.normal(size=5)); w = unit(project(x, rng.normal(size=5)))print("R_x(0) = x:", np.allclose(retract(x, 0 * w), x))h = 1e-6print("first order: dR_x(tw)/dt at 0 = w:", np.allclose((retract(x, h * w) - retract(x, -h * w)) / (2 * h), w, atol=1e-6))eps = np.array([0.4, 0.2, 0.1, 0.05, 0.025])err = np.array([np.linalg.norm(retract(x, e * w) - exp_map(x, e * w)) for e in eps]) # distance between the retraction and the exponential maporder = np.diff(np.log(err)) / np.diff(np.log(eps)) # slope of log(error) against log(eps)print("errors:", err)print("observed orders:", order, "(expected 3)")
The observed orders are $2.90,\ 2.97,\ 2.99,\ 3.00$, converging to 3. The values agree with the proof: for $|v|=0.4$ the error is $0.0195$ and $\varepsilon^3/3=0.0213$ (the remaining terms are of order $\varepsilon^4$).
Exercise 3.2 · descent with a retraction
- Write a generic Riemannian gradient descent with a function
move(x, v)and a stopping test on the norm of the gradient. - Run it with the exponential map and with the retraction from the same starting point.
- Compare the numbers of iterations and the final values with $\lambda_{\min}$.
def riemannian_gd_generic(x0, step, move, tol=1e-8, max_iter=5000): x = x0 for k in range(max_iter): g = rgrad(x) if np.linalg.norm(g) < tol: return x, k x = ... # TO DO: the same loop with any way of moving: Exp or retraction return x, max_iterx0 = unit(np.random.default_rng(5).normal(size=n))step = 0.5 / (lam[-1] - lam[0])x_exp, k_exp = riemannian_gd_generic(x0, step, exp_map)x_ret, k_ret = riemannian_gd_generic(x0, step, retract)print("exponential map:", k_exp, "iterations, f =", f(x_exp))print("retraction :", k_ret, "iterations, f =", f(x_ret))print("smallest eigenvalue:", lam[0])
Show the correction
def riemannian_gd_generic(x0, step, move, tol=1e-8, max_iter=5000): x = x0 for k in range(max_iter): g = rgrad(x) if np.linalg.norm(g) < tol: return x, k x = move(x, -step * g) # the same loop with any way of moving: Exp or retraction return x, max_iterx0 = unit(np.random.default_rng(5).normal(size=n))step = 0.5 / (lam[-1] - lam[0])x_exp, k_exp = riemannian_gd_generic(x0, step, exp_map)x_ret, k_ret = riemannian_gd_generic(x0, step, retract)print("exponential map:", k_exp, "iterations, f =", f(x_exp))print("retraction :", k_ret, "iterations, f =", f(x_ret))print("smallest eigenvalue:", lam[0])
Both versions stop after 77 iterations at the minimum value $-3$: the discrepancy of order $|v|^3$ between the two moves is negligible compared with the step, and it vanishes as the gradient does. On the sphere the retraction is cheaper (no trigonometric function), and on matrix manifolds this difference is decisive.
Part 4 · Natural gradient and information geometry
The Fisher metric and the natural gradient
A parametric family of probability densities $p_\theta$ is a manifold whose points are distributions. The natural metric is the Fisher information $F(\theta)=\mathbb E_{y\sim p_\theta}\big[\nabla_\theta\log p_\theta(y)\,\nabla_\theta\log p_\theta(y)^{\top}\big]$. For a loss $\mathcal L(\theta)$ (for instance the negative log-likelihood), the Riemannian gradient for the metric $F$ is $F(\theta)^{-1}\nabla\mathcal L(\theta)$, called the natural gradient, and gradient descent for the Fisher metric is
\[\theta_{t+1}=\theta_t-\alpha\,F(\theta_t)^{-1}\nabla\mathcal L(\theta_t)\](the exponential map is replaced by the retraction $\theta\mapsto\theta+v$, as in Part 3). Example: the Gaussian family $N(\mu,\sigma^2)$ in the parameters $(\mu,\sigma)$. The score is $\big(\frac{y-\mu}{\sigma^2},\ \frac{(y-\mu)^2-\sigma^2}{\sigma^3}\big)$, and its second moments give $F=\operatorname{diag}(1/\sigma^2,\ 2/\sigma^2)$.
Why this metric? It is the one that measures how different two distributions are.
$\operatorname{KL}(p_\theta\,\|\,p_{\theta+\delta})=\tfrac12\,\delta^{\top}F(\theta)\,\delta+O(|\delta|^3)$.
Proof
Let $\ell(\theta')=\mathbb E_{p_\theta}[\log p_{\theta}-\log p_{\theta'}]$. Then $\ell(\theta)=0$. Its gradient at $\theta'=\theta$ is $-\mathbb E[\nabla\log p_\theta]=0$ (the expected score is zero because $\int p_\theta=1$). Its Hessian at $\theta'=\theta$ is $-\mathbb E[\nabla^2\log p_\theta]=F(\theta)$ (the information identity, obtained by differentiating $\int\nabla p_\theta=0$ once more). A Taylor expansion at order 2 gives the claim. $\square$
Consequently, a step $\delta$ of fixed “length” $\delta^{\top}F\delta$ changes the distribution by a fixed amount in KL, and the steepest descent direction for this length is the natural gradient (Part 1): the natural gradient is the steepest descent in distribution space, independently of the parametrization.
Exercise 4.1 · gradient against natural gradient
- Write the Fisher matrix of $N(\mu,\sigma^2)$ in the parameters $(\mu,\sigma)$ and check it by a Monte Carlo estimate of the expected outer product of the score.
- Minimize the negative log-likelihood of 2,000 observations of $N(3,0.5^2)$ from $(\mu,\sigma)=(0,2)$, with the gradient and with the natural gradient.
- Count the iterations needed to get within $10^{-3}$ of the maximum-likelihood estimate.
data = np.random.default_rng(3).normal(3.0, 0.5, size=2000) # observations from N(3, 0.5^2)xbar, s2 = data.mean(), data.var()def nll_grad(theta): mu, sigma = theta g_mu = (mu - xbar) / sigma ** 2 g_sigma = 1 / sigma - (s2 + (xbar - mu) ** 2) / sigma ** 3 return np.array([g_mu, g_sigma])def fisher(theta): mu, sigma = theta return ... # TO DO: Fisher information matrix of N(mu, sigma^2) in the parameters (mu, sigma)# check the Fisher matrix: E[score score^T] with the score = d log p / d theta, by Monte Carlotheta = np.array([1.0, 2.0])y = np.random.default_rng(4).normal(theta[0], theta[1], size=1_000_000)score = np.stack([(y - theta[0]) / theta[1] ** 2, ((y - theta[0]) ** 2 - theta[1] ** 2) / theta[1] ** 3], axis=1)print("Monte Carlo Fisher:\n", score.T @ score / len(y), "\nexact:\n", fisher(theta))def descend(theta0, step, natural, n_iter=2000, tol=1e-3): th = np.array(theta0, float) for k in range(n_iter): g = nll_grad(th) if natural: g = ... # TO DO: natural gradient: F^{-1} grad (the gradient for the Fisher metric) th = th - step * g if abs(th[0] - xbar) < tol and abs(th[1] - np.sqrt(s2)) < tol: return th, k + 1 return th, n_iterprint("maximum likelihood estimate:", xbar, np.sqrt(s2))for name, natural, step in [("gradient, step 0.05", False, 0.05), ("gradient, step 0.5", False, 0.5), ("natural gradient, step 0.5", True, 0.5)]: th, k = descend([0.0, 2.0], step, natural) print(f"{name:28s}: {k:5d} iterations, theta = {th}")
Show the correction
data = np.random.default_rng(3).normal(3.0, 0.5, size=2000) # observations from N(3, 0.5^2)xbar, s2 = data.mean(), data.var()def nll_grad(theta): mu, sigma = theta # Gradient of the mean negative log-likelihood log(sigma) + (x - mu)^2 / (2 sigma^2). g_mu = (mu - xbar) / sigma ** 2 g_sigma = 1 / sigma - (s2 + (xbar - mu) ** 2) / sigma ** 3 return np.array([g_mu, g_sigma])def fisher(theta): mu, sigma = theta return np.diag([1 / sigma ** 2, 2 / sigma ** 2]) # Fisher information matrix of N(mu, sigma^2) in the parameters (mu, sigma)# check the Fisher matrix: E[score score^T] with the score = d log p / d theta, by Monte Carlotheta = np.array([1.0, 2.0])y = np.random.default_rng(4).normal(theta[0], theta[1], size=1_000_000)score = np.stack([(y - theta[0]) / theta[1] ** 2, ((y - theta[0]) ** 2 - theta[1] ** 2) / theta[1] ** 3], axis=1)print("Monte Carlo Fisher:\n", score.T @ score / len(y), "\nexact:\n", fisher(theta))def descend(theta0, step, natural, n_iter=2000, tol=1e-3): th = np.array(theta0, float) for k in range(n_iter): g = nll_grad(th) if natural: g = np.linalg.solve(fisher(th), g) # natural gradient: F^{-1} grad (the gradient for the Fisher metric) th = th - step * g if abs(th[0] - xbar) < tol and abs(th[1] - np.sqrt(s2)) < tol: return th, k + 1 return th, n_iterprint("maximum likelihood estimate:", xbar, np.sqrt(s2))for name, natural, step in [("gradient, step 0.05", False, 0.05), ("gradient, step 0.5", False, 0.5), ("natural gradient, step 0.5", True, 0.5)]: th, k = descend([0.0, 2.0], step, natural) print(f"{name:28s}: {k:5d} iterations, theta = {th}")
The Monte Carlo matrix, $\begin{pmatrix}0.2496&-0.0001\\-0.0001&0.4963\end{pmatrix}$, matches the exact $\operatorname{diag}(0.25,0.5)$ at $\theta=(1,2)$. Natural gradient with step $0.5$ needs 16 iterations; the plain gradient needs 167 (step $0.05$) or 223 (step $0.5$): about ten times more here. The natural gradient divides each component by the right scale ($\sigma^2$ for $\mu$, $\sigma^2/2$ for $\sigma$), so that its steps do not depend on how the parameters are scaled.
Exercise 4.2 · the Fisher metric is the second-order expansion of the KL divergence
- Write the KL divergence between two Gaussians.
- For a fixed $\delta$ scaled by $1,\ 0.5,\ 0.25,\ 0.1,\ 0.05$, compare $\operatorname{KL}(p_\theta\|p_{\theta+\delta})$ with $\tfrac12\delta^{\top}F\delta$.
- What do the ratios tend to?
def kl(t1, t2): """KL( N(mu1, s1^2) || N(mu2, s2^2) ).""" (m1, s1), (m2, s2) = t1, t2 return np.log(s2 / s1) + (s1 ** 2 + (m1 - m2) ** 2) / (2 * s2 ** 2) - 0.5theta = np.array([1.0, 2.0])delta = np.array([0.6, -0.3])for scale in [1.0, 0.5, 0.25, 0.1, 0.05]: dl = scale * delta exact = kl(theta, theta + dl) quad = ... # TO DO: the quadratic form 1/2 delta^T F delta print(f"|delta| scale {scale:5.2f}: KL = {exact:.3e}, 1/2 delta^T F delta = {quad:.3e}, ratio = {exact / quad:.4f}")
Show the correction
def kl(t1, t2): """KL( N(mu1, s1^2) || N(mu2, s2^2) ).""" (m1, s1), (m2, s2) = t1, t2 return np.log(s2 / s1) + (s1 ** 2 + (m1 - m2) ** 2) / (2 * s2 ** 2) - 0.5theta = np.array([1.0, 2.0])delta = np.array([0.6, -0.3])for scale in [1.0, 0.5, 0.25, 0.1, 0.05]: dl = scale * delta exact = kl(theta, theta + dl) quad = 0.5 * dl @ fisher(theta) @ dl # the quadratic form 1/2 delta^T F delta print(f"|delta| scale {scale:5.2f}: KL = {exact:.3e}, 1/2 delta^T F delta = {quad:.3e}, ratio = {exact / quad:.4f}")
The ratios are $1.360,\ 1.159,\ 1.075,\ 1.029,\ 1.014$ for $\delta$ scaled by $1,\ 0.5,\ 0.25,\ 0.1,\ 0.05$: they tend to 1 linearly in $|\delta|$, as the $O(|\delta|^3)$ remainder predicts relative to the quadratic term.
Part 5 · Deliverables and limits
Build a defensible report
- Prove the rate $\rho(\alpha)$ of gradient descent on a quadratic and the optimal step.
- Prove that the Riemannian gradient is the direction of steepest descent for the metric $G$.
- Derive the Riemannian gradient of the Rayleigh quotient and show that its critical points are eigenvectors.
- Report convergence curves for three step sizes and the stability limit.
- Show that the retraction has order 3 with respect to the exponential map (proof and numerics).
- Compare gradient and natural gradient, and prove $\operatorname{KL}\approx\tfrac12\delta^{\top}F\delta$.
- Extension: minimize a function of your choice on the group of rotations $SO(3)$ or on the set of unit-norm vectors with a non-Euclidean metric, using a retraction.
What these notes leave out
We gave rates only for quadratic functions and the stability limit by a Hessian argument, without a global convergence proof. For smooth functions on manifolds the theory (Lipschitz Riemannian gradients, Armijo line search, Newton and trust-region methods) is in the references. The natural gradient requires $F^{-1}$: for neural networks $F$ is huge and approximations are used. In the Gaussian example $F$ is exact and diagonal, which is why the gain is so clean; on real models the gain is smaller and the cost per step is higher.
References and related learning
Books and papers
- N. Boumal, An Introduction to Optimization on Smooth Manifolds, Cambridge University Press, 2023.
- P.-A. Absil, R. Mahony, R. Sepulchre, Optimization Algorithms on Matrix Manifolds, Princeton University Press, 2008 (retractions, Rayleigh quotient).
- S. Amari, Natural gradient works efficiently in learning, Neural Computation 10(2), 1998.
- J. Martens, New insights and perspectives on the natural gradient method, JMLR 2020.
- Previous course: Riemannian Geometry. Original article on this site: Optimization and Gradient Descent on Riemannian Manifolds (notes). See also Stochastic gradient descent.