Interpolate between two latent vectors with slerp

Why it matters Latent interpolation videos from GANs and VAEs, and seed blending in image generators, use slerp.

Walking in a straight line between two Gaussian latents passes through points with unusually small norm, which decode to washed-out images. Spherical interpolation follows the arc instead.

Write slerp(z0, z1, ts). z0 and z1 are (d,) arrays, ts is a list of values in [0, 1]. Let omega = arccos(clip(u0 . u1, -1, 1)) where u0, u1 are z0, z1 divided by their norms. If sin(omega) < 1e-6, use linear interpolation (1 - t) * z0 + t * z1. Otherwise return sin((1 - t) * omega) / sin(omega) * z0 + sin(t * omega) / sin(omega) * z1. Return a (len(ts), d) float array.

Signaturedef slerp(z0, z1, ts)

Example

slerp([1, 0], [0, 1], [0, 0.5, 1]) is about [[1, 0], [0.7071, 0.7071], [0, 1]], while linear interpolation would give [0.5, 0.5] in the middle.

Understand the idea

High-dimensional Gaussian samples almost all sit near a sphere of the same radius. A straight line between two of them cuts through the inside of the sphere, where real samples almost never are, so the middle images look dull. Slerp walks along the surface instead, like flying along the curve of the Earth rather than tunnelling through it.

Tiny example: z0 = [1, 0], z1 = [0, 1], 90 degrees apart. At t = 0.5 the weights are sin(45 deg) / sin(90 deg) = 0.707 each, giving [0.707, 0.707], which still has length 1. The straight-line midpoint [0.5, 0.5] has length only 0.707.

Rule: omega = arccos(u0 . u1); slerp(t) = sin((1 - t) omega) / sin omega * z0 + sin(t omega) / sin omega * z1.

GAN and diffusion demos use slerp to morph smoothly between two generated images.

Shapes and data flow

z0, z1 (d,) -> output (len(ts), d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleslerp([1.0, 0.0], [0.0, 1.0], [0.0, 0.5, 1.0])
  • Sample 2: different normsslerp([2.0, 0.0, 0.0], [0.0, 3.0, 4.0], [0.25, 0.75])
  • Test 3: parallel falls backslerp([1.0, 1.0], [2.0, 2.0], [0.5])
  • Test 4: 45 degreesslerp([0.6, 0.0], [0.5, 0.5], [0.3, 0.6])