Flow matching on the sphere (Riemannian flow matching)
Before this lesson: flow matching in : the marginalization trick, the CFM loss and Euler sampling (lesson 14); coordinates on the sphere (lesson 09); matrix manifolds, tangent spaces and projections (linear algebra 19). Time: about 80 minutes, plus the notebook.
Why this matters #
- Events on the Earth. Earthquake epicentres, volcanic eruptions, floods and wildfires are points on the sphere. Chen and Lipman (ICLR 2024) test Riemannian flow matching on exactly these four Earth-science catalogues (compiled by Mathieu and Nickel, 2020). A density model on the sphere gives hazard maps and synthetic catalogues.
- Other curved spaces. Wind directions live on a circle, protein backbone angles on a torus, and the orientation of a rigid body (or of a fault plane with its slip direction) in the rotation group . The same tools (exp, log, tangent projections, retractions) build flow models on all of them.
- No new training cost. On the sphere, geodesics have a closed form, so training stays simulation-free, as in lesson 14. In flat space the method is exactly the CFM of lesson 14.
Do not confuse this lesson with lesson 09. Lesson 09 is about fields on the sphere (a value at every point, such as temperature). This lesson is about probability distributions of points on the sphere (where events happen).
1. Predict first #
2. The picture #
The simplest case: the circle #
A point on the circle is an angle , and a velocity is one number. The shortest way from to is the shorter arc, of length , where maps an angle to . Moving with velocity for unit time gives , and the velocity that reaches in unit time is . So flow matching on the circle is the flow matching of lesson 14 with one change: the difference becomes the wrapped difference.
At one point, , the two arcs are equally short and the wrapped difference jumps from to . That point is the trouble spot on every sphere.
The sphere: tangent planes and great circles #
A point is a unit vector . The velocities of curves through form the tangent plane: the vectors orthogonal to . A straight line leaves the sphere at once. The "straight lines" of the sphere are the great circles: walk a distance from in the unit tangent direction and you arrive at .
Move the direction and the length of ; then press "|v| > π". The point (dark), its tangent plane (blue patch) and a tangent vector (orange, drawn at half length). walks the distance along the great circle (yellow) in the direction of . Violet: , the way back. For it equals (the arrows overlap). For the walk passes the opposite point, and the log gives the shorter way round: a different vector. Drag the sphere to turn it.
The recipe #
Riemannian flow matching is lesson 14 with three replacements:
| Lesson 14 () | On the sphere |
|---|---|
| , the great-circle path | |
| target velocity | , tangent at |
| Euler step | , or |
and one constraint: the network's velocity must be tangent, so we project its output onto the tangent plane.
A network outputs at the north pole . Which tangent velocity does the model use after the projection ?
. The normal part along is removed. Dividing by the norm (first option) gives a unit vector that is still not tangent. is the part that is removed, not the part that is kept.
3. Definitions and main results #
The sphere as a Riemannian manifold #
- . In this track (lesson 09), a point with colatitude and longitude is . With latitude , this is the usual map coordinate.
- Tangent plane. For a curve on , differentiate : . So , and the orthogonal projection onto it is , that is, .
- Metric. The inner product of two tangent vectors is their dot product in (the sphere is a Riemannian submanifold of ). The length of a curve is . The geodesic distance is the length of the shortest curve: , the angle between and (times the radius, 6371 km, on the Earth).
- Geodesics are curves with no tangential acceleration. For a unit and a tangent , has . This is normal to the sphere, so : great circles at constant speed are the geodesics.
- The exponential map is the point reached at time 1 by the geodesic that starts at with velocity . The logarithm map is its inverse: the shortest tangent vector with . In : and .
Theorem 1 (exponential and logarithm maps of the sphere) #
For and ,
For with , let and . Then
and , , and whenever .
- is for the great circle above, with and . It has norm 1 because : .
- Let with . Take the dot product with : . Since is one-to-one on , .
- The tangent part of is . Since , the unit vectors agree: . With step 2, , which is the formula for , and .
- Conversely, .
Where log fails. At , , and every tangent direction gives a geodesic of length to : is not defined there. The set of points where the shortest geodesic from stops being unique is the cut locus of ; on the sphere it is the single point . Near it, the direction of jumps when moves a tiny distance.
Turn β, then make δ small. is the north pole. Two points and sit at distance from the south pole, on opposite sides. They are only apart, but their log vectors at (arrows, half length) point in opposite directions, each of length : the shortest great circle goes down one side of the sphere or the other. As β turns, turns all the way round. A training target built from is discontinuous at the antipode.
Geodesic interpolation. Put into and use :
This is slerp (spherical linear interpolation). It runs along the great circle at the constant speed , from at to at .
Theorem 2 (the velocity of the geodesic path) #
For and :
Why it is true, in words. At time the point still has the distance to go along the same great circle, and it must cover it in the time . The log map points along the circle and has the length of the remaining distance; dividing by the remaining time gives the speed .
Proof of Theorem 2
- with is a geodesic with constant speed .
- The rest of the path, for , is again a geodesic. It starts at , ends at , and its length is .
- By Theorem 1, the only tangent vector at of norm below whose geodesic reaches at time 1 is . So the initial velocity of the curve in step 2 is .
- By the chain rule, that initial velocity is . Hence .
This is the conditional velocity of Chen and Lipman. In , : the CFM target of lesson 14. The geodesic path is the sphere's version of a straight path: one exponential-map step from with the velocity lands exactly on .
Move , then try the presets. Blue: the geodesic path from to . Yellow: ; orange: its velocity at half length. The speed readout is the same for every : it is the distance . Magenta dashed: the straight chord of flow matching in . It runs inside the ball: from the North Pole to the equator, its midpoint is 1866 km below the surface.
is the North Pole and is on the equator. What is the velocity of the geodesic path at ?
By Theorem 2 at , with and . The chord velocity is not tangent (it has a -component). The unit direction is right, but the speed must be the distance , so that the point arrives at .
Theorem 3 (Riemannian conditional flow matching) #
Setup. A source on (for example uniform), data on , a coupling of the two (independent by default), , the path , and the conditional target . Let be the law of , and the marginal velocity. Norms of tangent vectors are Euclidean norms in .
- Marginalization trick on manifolds (Flow Matching Guide, Theorem 10, under its regularity assumptions): generates , so the ODE started from ends at . The proof is Theorem 1 of lesson 14 with test functions on the sphere.
- RCFM (Flow Matching Guide, Theorem 11): for a velocity network , let and . Then : the same gradients and the same minimizer .
Proof of the RCFM statement. It is the proof of Theorem 2 in lesson 14, word for word:
- Expand .
- is the same in both losses, because .
- Cross term, by the tower property: . All vectors here lie in the same tangent plane , where the inner product is the one of .
- The remaining terms do not contain .
Nothing in the proof uses flatness. Two practical conditions:
- The model must be tangent: for any network with output in . Otherwise the learned ODE pushes samples off the sphere.
- Avoid antipodal pairs: has probability zero for continuous and , but near-antipodal pairs give unstable targets; skip or clamp them.
Simulation-free. On the sphere, and its target have closed forms, so a training step needs no ODE solve: sample , compute and the target, regress. On a general manifold (a triangle mesh, say) geodesics have no closed form. Chen and Lipman then build a distance from the eigenfunctions of the Laplace–Beltrami operator (on the sphere these would be the spherical harmonics of lesson 09), and they must simulate the conditional path during training.
Chen and Lipman's general formula (premetrics)
Chen and Lipman define the conditional flow through a premetric (zero only at ) and a decreasing scheduler with , . The flow is built so that , and its velocity is
With and the geodesic distance, has norm 1, and the formula gives : Theorem 2 again. With a spectral distance on a mesh the same formula still works, but has no closed form.
Sampling on the sphere #
The exact flow of a tangent field stays on the sphere: . Numerical steps of size behave differently:
- Plain Euler : since , . Every step moves outward, and the error adds up.
- Exponential-map Euler : a step along the great circle.
- Projected Euler : a retraction, that is, a cheap map from the tangent plane back to the manifold that matches the exponential map at least to first order. This one is even better. It moves by the angle instead of , and since , it matches the exponential map to second order.
Both keep the samples on the sphere up to round-off, and both are first-order methods like Euler. The
RiemannianODESolver of Meta's flow_matching library projects the velocity onto the tangent plane and the
point back onto the sphere after each Euler, midpoint or RK4 step.
Move the number of steps and change the target. All three samplers follow the conditional velocity from the North Pole to . Magenta: plain Euler, whose points float above the surface (norm 1.86 after one step to the equator). Orange: projected Euler; it stays on the sphere but lags behind, and the lag shrinks quickly with . Blue: exponential-map Euler, exact for every , because each step covers the fraction of the remaining distance along the same great circle.
One plain Euler step of size from the North Pole with the velocity . What is the norm of the new point?
, because . A tangent velocity keeps the exact flow on the sphere, but a finite straight step always leaves it. The norm is not , because the two parts are orthogonal.
Answers to section 1. (1) At the origin: . In general, for and . So the paths run through the interior of the ball, the network must learn a 3D flow for 2D data, and nothing forces the final samples onto the sphere. (2) Outside: .
4. Worked example #
(a) From the North Pole to the equator. and (latitude 0, longitude 0).
- Distance: . On the Earth that is km.
- Tangent part: , with . So .
- Path: . At : , at latitude 45°. The straight-line midpoint has norm : on the Earth it lies km below the surface.
- Velocity by differentiation: , so , with speed at every .
- Check Theorem 2 at . The distance left is . The tangent part of at is , with unit vector . So . Dividing by gives , as in step 4.
(b) One step of each sampler from , with the velocity .
- Plain Euler: , of norm : far off the sphere.
- Projected Euler: . It moved by the angle (57.5°), so it is still (32.5°) away from .
- Exponential map: , exactly.
With steps along the conditional field (section 5): plain Euler ends at norms , , , for ; projected Euler ends , , , away from ; the exponential map is exact for every .
(c) Near the antipode. and (normalized). The two points are apart, but : opposite directions. A target that depends on is discontinuous there.
5. In code #
SciPy's rotations and geometric_slerp check the formulas of section 3:
import numpy as np
from scipy.spatial import geometric_slerp
from scipy.spatial.transform import Rotation
def exp_map(x, v):
n = np.linalg.norm(v)
return x if n == 0 else np.cos(n) * x + np.sin(n) * v / n
def log_map(x, y):
u = y - (x @ y) * x # P_x y, the tangent part of y
return np.arccos(np.clip(x @ y, -1, 1)) * u / np.linalg.norm(u)
rng = np.random.default_rng(0)
x, y = rng.standard_normal((2, 3))
x, y = x / np.linalg.norm(x), y / np.linalg.norm(y)
v = log_map(x, y)
print(abs(x @ v), np.linalg.norm(exp_map(x, v) - y)) # 2.8e-17 1.6e-16: tangent, and exp(log y) = y
print(np.linalg.norm(v), np.arccos(x @ y)) # 0.7616 0.7616: |log_x y| = geodesic distance
# exp_x(w) is a rotation of x by the angle |w| about the axis x × w / |w|: rotvec = x × w.
w = np.cross(x, rng.standard_normal(3))
w = 2.5 * w / np.linalg.norm(w) # a tangent vector at x with |w| = 2.5 < pi
print(np.linalg.norm(exp_map(x, w) - Rotation.from_rotvec(np.cross(x, w)).apply(x)),
np.linalg.norm(log_map(x, exp_map(x, w)) - w)) # 1.6e-16 4.4e-16: log(exp w) = w for |w| < pi
# The geodesic path exp_x(t log_x y) is SciPy's spherical interpolation (slerp).
t = np.linspace(0, 1, 7)
path = np.array([exp_map(x, s * v) for s in t])
print(np.abs(path - geometric_slerp(x, y, t)).max()) # 2.5e-16
# Its velocity, by central differences, equals log_{x_t}(y) / (1 - t), with constant speed d(x, y).
s, h = 0.3, 1e-6
xt = exp_map(x, s * v)
vel = (exp_map(x, (s + h) * v) - exp_map(x, (s - h) * v)) / (2 * h)
print(np.linalg.norm(vel - log_map(xt, y) / (1 - s)), np.linalg.norm(vel) - np.arccos(x @ y)) # 5.8e-11 -4.3e-11
Then (same session) the three samplers on the conditional field of worked example (b), and the antipode of (c):
x0, x1 = np.array([0.0, 0.0, 1.0]), np.array([1.0, 0.0, 0.0])
u = lambda x, t: log_map(x, x1) / (1 - t)
angle = lambda z: np.arccos(np.clip(z @ x1 / np.linalg.norm(z), -1, 1)) # angle between z and x1
for N in (1, 2, 5, 10):
h = 1 / N
xe, xp, xr = x0.copy(), x0.copy(), x0.copy()
for k in range(N):
t = k * h
xe = xe + h * u(xe / np.linalg.norm(xe), t) # plain Euler (field read at the radial projection)
xp = xp + h * u(xp, t); xp /= np.linalg.norm(xp) # projected Euler (a retraction)
xr = exp_map(xr, h * u(xr, t)) # exponential-map Euler
print(N, round(np.linalg.norm(xe), 4), round(angle(xp), 4), round(angle(xr), 12))
# N |x| plain Euler angle to x1 (projected) angle to x1 (exp map)
# 1 1.8621 0.5669 0.0
# 2 1.5607 0.1694 0.0
# 5 1.2556 0.0118 0.0
# 10 1.1283 0.0014 0.0
x = np.array([0.0, 0.0, 1.0])
for e in (1e-8, -1e-8):
y = np.array([e, 0.0, -1.0]); y /= np.linalg.norm(y)
print(log_map(x, y).round(4)) # [ 3.1416 0. 0.], then [-3.1416 0. 0.]
6. Where it shows up #
- Earth-science event data. Chen and Lipman's sphere benchmarks are catalogues of volcanic eruptions, earthquakes, floods and fires (compiled by Mathieu and Nickel, 2020, from NOAA, the Dartmouth Flood Observatory and NASA fire data). They report test log-likelihoods for each.
- Seismology and weather. Epicentre densities for seismic hazard; cyclone genesis points and lightning on ; wind directions on the circle; focal mechanisms (strike, dip and rake) as rotations in , up to the symmetries of the double couple.
- Proteins and robotics. Flow matching on and (for example FrameFlow and FoldFlow) generates protein backbones as rigid frames; Chen and Lipman also model protein dihedral angles on tori.
- Software. Meta's open-source
flow_matchinglibrary has aSpheremanifold (expmap,logmap,projx,proju), a geodesic probability path and aRiemannianODESolver, with a sphere example notebook.
7. Common mistakes #
- A velocity model that is not tangent. Without , normal components push samples off the sphere. Project the output, and project the input point too if it may have drifted.
- Plain Euler steps. They leave the sphere at every step; use the exponential map or project.
arccoswithout clipping. Round-off can give (the next float above 1), andarccosreturns NaN. Clip to .- Dividing by . For close to , ; switch to it below a small threshold.
- A "uniform" source made from uniform latitude and longitude. The area element is , so uniform latitudes pile up mass near the poles. Normalize a standard 3D Gaussian instead: its density depends only on , so its direction is uniform.
- Different base points. Chen and Lipman write ; other code computes . Both are the same great-circle path when the geodesic is unique.
- Fields versus points. SFNO (lesson 09) maps fields on the sphere to fields; Riemannian flow matching models where points fall on the sphere.
8. Check yourself #
- Compute and for and . How far apart are the two points
on the Earth?
Answer
, so . , with . . On the Earth: km. - A projected Euler step and an exponential-map step use the same tangent step of length . By how
much do the angles they move differ?
Answer
The projected step moves , the exponential map : a difference of . - Show that RCFM with the geodesic path is the CFM of lesson 14 when the manifold is .
Answer
In , and . So , and the target . The tangent projection is the identity. - Why is training simulation-free on the sphere but not on a general triangle mesh?
Answer
On the sphere, and have closed forms, so and the target are computed directly. On a mesh, geodesics have no closed form; Chen and Lipman use a spectral distance instead, and then must be found by solving the ODE of the conditional velocity. - Your trained model's samples have . Name two likely causes.
Answer
Plain Euler steps (each adds to ), or a velocity network whose output is not projected onto the tangent plane. With exp-map or projected steps and a tangent model, the error is at round-off level. - Is for ? Explain with a picture.
Answer
No. Walking 4 > π along the great circle passes the antipode ; the end point is closer to the other way round, at distance . The log gives that shorter way: a vector of length pointing opposite to .
What is the projection onto the tangent plane of at ?
, that is, .
What is the geodesic distance between unit vectors and on ?
, the angle between them.
Write the exponential map of the sphere.
for a tangent vector .
Write the logarithm map of the sphere.
with and (for ).
Why is undefined at ?
Every tangent direction gives a shortest geodesic of length to , so there is no unique shortest vector ().
What is the velocity of the geodesic path ?
, with constant length .
Write the Riemannian CFM loss.
with and a tangent model .
One plain Euler step with tangent : what is ?
, always larger than 1.
Why use a retraction such as when sampling?
It keeps the samples on the sphere at almost no cost and agrees with the exponential map to second order.
9. Interview angle #
- "How would you build a generative model of earthquake epicentres?" Convert latitude and longitude to unit vectors, use a uniform source on , the geodesic path, a tangent-projected MLP velocity, the RCFM loss, and an exponential-map or projected ODE solver. Evaluate the test log-likelihood, as Chen and Lipman do.
- "Why not just normalize the output of a Euclidean model?" The training paths and the model live in (through the Earth), and the normalization is not part of the learned flow. It can work, but it wastes capacity, and the density on the sphere is not modelled directly.
- "Diffusion or flow matching on manifolds?" Manifold diffusion models need simulation during training and approximations of the score on the manifold; Riemannian flow matching is simulation-free on simple manifolds such as the sphere.
- "What goes wrong numerically?" Points leaving the manifold, NaNs from
arccos, division by near , and unstable directions near the antipode. - "What is the analogue of the OT straight path on a manifold?" The geodesic interpolation; in it is the conditional OT path of lesson 14.
10. Practice #
The notebook for this lesson runs in Colab or in the browser. It has five exercises, each with a check cell and a folded solution:
- The exponential and logarithm maps of and the round-trip test.
- The geodesic path equals slerp (
scipy.spatial.geometric_slerp). - The velocity of the geodesic path by central differences equals .
- Plain, projected and exponential-map Euler on the conditional velocity.
- A data set of three clusters on the sphere: the exact marginal velocity (a weighted average of conditional velocities) and sampling from the uniform distribution to the clusters.
11. Watch and read #
- Chen and Lipman, Flow Matching on General Geometries (ICLR 2024): §3.1 (Riemannian flow matching and the RCFM objective), §3.2 (premetrics and the geodesic distance), §3.3 (spectral distances), §5 (the Earth-science data sets).
- Lipman et al., Flow Matching Guide and Code (2024): §5.3–5.6 (paths on manifolds, Theorems 10 and 11, the geodesic conditional flow, the antipodal singularity).
- Boumal, An Introduction to Optimization on Smooth Manifolds (2023, free): §3.6 (retractions on the sphere), §5.8 (great circles are geodesics), §7.2 (the unit sphere), §10.2 (exp and log of the sphere).
- Holderrieth and Erives, An Introduction to Flow Matching and Diffusion Models (2025): the MIT 6.S184 lecture notes.
- Meta,
flow_matchingsphere example: Riemannian flow matching on the sphere in PyTorch.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.