Run an affine coupling layer forward and backward

Why it matters Flow layers like this power exact-likelihood generative models and parts of audio vocoders.

Normalising flows like RealNVP use coupling layers that are trivially invertible.

Write coupling(x, s_fn, t_fn, reverse=False). Split each row of x (n, d) into x1 = x[:, :d//2] and x2 = x[:, d//2:]. Forward: y2 = x2 * exp(s_fn(x1)) + t_fn(x1), y1 = x1, log_det = sum of s_fn(x1) per row. Reverse (x is then y): x2 = (y2 - t_fn(y1)) * exp(-s_fn(y1)). Return (output, log_det) where log_det is the forward log-determinant, or its negative in reverse mode.

Signaturedef coupling(x, s_fn, t_fn, reverse=False)

Example

with s_fn and t_fn returning zeros, the layer is the identity and log_det is 0.

Understand the idea

A normalising flow needs layers that are easy to invert and whose Jacobian determinant is cheap. An affine coupling layer splits each vector in half. The first half passes through unchanged and is used to compute a scale s and shift t for the second half. Since the second half never affects s or t, you can always undo it. Worked example: x = [[1, 2]], so x1 = 1 and x2 = 2. Let s_fn(x1) = x1 * ln 2 = 0.693 and t_fn(x1) = 3 * x1 = 3. Forward: y2 = 2 * exp(0.693) + 3 = 2 * 2 + 3 = 7, y1 = 1, log_det = 0.693. Reverse from y = [[1, 7]]: x2 = (7 - 3) * exp(-0.693) = 4 / 2 = 2, recovered exactly, and log_det = -0.693. Rule: forward y1 = x1, y2 = x2 * exp(s(x1)) + t(x1), log_det = row sum of s(x1). Reverse x1 = y1, x2 = (y2 - t(y1)) * exp(-s(y1)), log_det = minus the row sum of s(y1). Subtract t first, then undo the scale. Used in: RealNVP and Glow style flows.

Shapes and data flow

x (n, d) -> x1 (n, d/2) | x2 (n, d/2)
s(x1), t(x1) (n, d/2)
y = [x1 | x2 * exp(s) + t], log_det (n,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecoupling(_x, lambda a: np.zeros_like(a), lambda a: np.zeros_like(a))
  • Sample 2: forwardcoupling(_x, _s, _t)