Schedule the KL weight with cyclical annealing

Why it matters Text VAEs and VAE-based latent models use KL annealing to avoid collapsing latents.

VAEs suffer posterior collapse if the KL term is at full weight from step 0. Cyclical annealing ramps it up repeatedly.

Write kl_beta(step, cycle_len, ramp_frac=0.5, beta_max=1.0). Position in cycle tau = (step % cycle_len) / cycle_len. Return beta_max * tau / ramp_frac if tau < ramp_frac else beta_max.

Signaturedef kl_beta(step, cycle_len, ramp_frac=0.5, beta_max=1.0)

Example

kl_beta(25, 100) is 0.5 and kl_beta(75, 100) is 1.0.

Understand the idea

A VAE loss has a reconstruction term and a KL term. If the KL term has full weight from the start, the decoder can learn to ignore the latent code completely (posterior collapse). Cyclical annealing gives the KL term a weight beta that ramps from 0 up to beta_max, holds there, and then restarts at 0 in the next cycle, again and again. Worked example: cycle_len 200, ramp_frac 0.5, beta_max 1. Step 50: tau = 50 / 200 = 0.25, below 0.5, so beta = 0.25 / 0.5 = 0.5. Step 150: tau = 0.75, past the ramp, so beta = 1. Step 230: 230 % 200 = 30, tau = 0.15, so beta = 0.3; the cycle has restarted. With ramp_frac 0.25 at step 25, tau = 0.125 and beta = 0.5. Rule: tau = (step % cycle_len) / cycle_len; beta = beta_max * tau / ramp_frac if tau < ramp_frac, else beta_max. The modulo is what makes it cycle; without it the ramp happens once. Used in: training text VAEs and other latent variable models where the decoder is strong enough to ignore the latent.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: example[kl_beta(25, 100), kl_beta(75, 100)]
  • Sample 2: next cyclekl_beta(110, 100)
  • Test 3: ramp 0.25[kl_beta(s, 40, 0.25, 2.0) for s in (0, 5, 10, 39, 45)]