Two Pressures on One Batch

Learning to CompressHard+30 XP+30

Two Pressures on One Batch

A VAE's encoder does not hand over a code. For each input it hands over a centre and a spread for every code entry, and the code is drawn from that little cloud. Training then scores the result with two terms that pull in opposite directions, and one number β\betaβ that sets the balance between them.

In this problem the random draws have already been made, so everything is deterministic. For one input xxx with PPP positions and a code with ddd entries:

steprule
draw the codezj=cj+sj εjz_j = c_j + s_j\,\varepsilon_jzj​=cj​+sj​εj​
decodex^i=∑jWij zj+bi\hat{x}_i = \sum_j W_{ij}\, z_j + b_ix^i​=∑j​Wij​zj​+bi​
reconstruction term1P∑i=1P(x^i−xi)2\dfrac{1}{P}\sum_{i=1}^{P} (\hat{x}_i - x_i)^2P1​∑i=1P​(x^i​−xi​)2
KL term12∑j=1d(cj2+sj2−1−ln⁡sj2)\dfrac{1}{2}\sum_{j=1}^{d}\left(c_j^2 + s_j^2 - 1 - \ln s_j^2\right)21​∑j=1d​(cj2​+sj2​−1−lnsj2​)

Here cjc_jcj​ is the centre, sjs_jsj​ the spread (always positive), and εj\varepsilon_jεj​ the draw from the standard shape at the origin (a standard normal), all for code entry jjj; ln⁡\lnln is the natural logarithm. The decoder is a single linear layer: weights WWW with one row per position and one column per code entry, and bias bbb.

Task: write vae_loss(inputs, centres, spreads, noise, weights, bias, beta).

  • Row nnn of centres, spreads and noise belongs to row nnn of inputs. The batch may hold a single input.
  • Average the reconstruction term over the batch, and separately average the KL term over the batch.
  • The loss is the average reconstruction term + β ×+\ \beta\ \times+ β × the average KL term, with β\betaβ given by beta.
  • Return [reconstruction, kl, loss], each rounded to 4 decimal places. Round only at the very end: the loss is built from the unrounded averages.

The two terms want different things. Reconstruction would like every input's cloud small and far from the others, so a draw can never be mistaken for a neighbour's. The KL term charges every cloud for straying from one standard shape at the origin. β\betaβ is the exchange rate, and the whole behaviour of a VAE lives in that trade.

Examples

inputs = [[1.0, 0.0, 2.0]]
centres = [[0.5, -1.0]]
spreads = [[0.5, 1.5]]
noise = [[1.0, -0.4]]
weights = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
bias = [0.0, 0.5, 0.0]
beta = 1.0
returns [2.6567, 1.1627, 3.8193]
inputs = [[2.0, -1.0], [0.0, 1.0]]
centres = [[1.0, 0.0], [-0.5, 0.5]]
spreads = [[0.8, 0.6], [1.2, 0.4]]
noise = [[0.5, -1.0], [-1.5, 2.0]]
weights = [[1.0, -1.0], [0.5, 1.0]]
bias = [0.2, -0.1]
beta = 0.5
returns [3.3756, 0.759, 3.7551]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run