If you have been following the fields of machine learning, you surely have come accross the idea of autoencoders already. They are networks that compress their input to a short description, and then rebuild the input from that description. As you can imagine, the computational cost of forwarding an uncompressed 3d flow in time is not cheap, which is why also in the fields of fluid dynamics, autoencoders are often times being utilized to compress the flow field into a lower dimensional latent space that the model works on instead.
This post builds the variational autoencoder (VAE) from scratch in the context of fluid dynamics. The first half shows what a VAE does and how it works by combining two loss terms together that actually fight each other. The second half than derives where that loss comes from and why it is built the way it is.
Why a flow can be compressed
The running example is the box of swirling water: a 64×64 grid in which every cell holds , the velocity to the right, and , the velocity upward. One snapshot is 64 · 64 · 2 = 8,192 numbers. In 3D, a 128³ box with three velocity components holds 128³ · 3 ≈ 6.3 million.
Most of these numbers are redundant. If the box holds a single swirl, four numbers describe it completely: centre x, centre y, size and spin speed. From those four, anyone can redraw all 8,192 values. This works because neighbouring cells hold nearly the same velocity: water cannot jump from 2 m/s to −2 m/s between neighbouring cells without friction smoothing the jump away (Post 12). Random noise is the opposite: no pattern, every value independent of its neighbours, so all 8,192 numbers are needed. A real flow sits in between, with many swirls of different sizes, but still full of structure that can be described with far fewer numbers.
Post 9 already compressed by hand: its spectral branch kept only the lowest frequencies, a rule a human picked. Here a network learns what to keep.
The autoencoder
An autoencoder is two networks in a row. The encoder maps the field to a much shorter list of numbers, the code. The length of this list is the code dimension, a design choice. Here it is 1,024, eight times fewer numbers than the field. The decoder maps the code back to a full field:
Both networks are trained together to give back their own input:
(1)
Where denotes the reconstruction loss, the rebuilt field, and the sum of the squared differences over all 8,192 values. Squaring makes every mistake positive and punishes big mistakes more: an error of 2 costs 4, an error of 0.5 costs 0.25.
$ autoencoder
// figure
bottleneckencoderdecoder8,1921,0248,192
bottleneckencoderdecoder8,1921,0248,192
The narrow middle is the bottleneck. The code cannot hold everything, so the network must keep what matters most for rebuilding: where the big swirls are, how strong they are, how they are shaped. A VAE that would be trained on generating faces for example, would instead learn to extracting features such as hair-color, eyes, male/female etc. No labels are ever needed, because the input is its own target - the training is therefore unsupervised.
Everything so far however, is also done by a plain autoencoder. The VAE keeps all of it and changes two things: what happens at the bottleneck, and one extra loss term.
Holes between the codes
Pretend the code has only 2 numbers. Then every snapshot is a dot on a sheet of paper, and 1,000 training snapshots are 1,000 dots. Equation (1) only checks that each training dot decodes to its own snapshot. It says nothing about the paper between the dots.
Take snapshot A, one swirl on the left, with code , and snapshot B, the same swirl slightly further right, with code . We would hope that the midpoint between and decodes to the swirl halfway between. Nothing forces that. The midpoint may decode to two faint half-swirls, or to a smeared pattern no real water would form. The encoder may even place and far apart, with unrelated flows in between.
This matters because we later want to work inside the code space: move a code to predict the next snapshot, or pick a new code to generate a new flow. Both need every region of the code space to mean a valid flow.
This bags the question, if a tiny change of the field throw its code somewhere completely different, the way a hash function such as SHA-256 does? The answer is no. SHA-256 is designed to jump: its bit operations scramble the input on purpose. An encoder is built from matrix multiplications, additions and activations such as ReLU. Each of them is continuous, and a chain of continuous operations is continuous.
Take a 4-number field and a 2-number code. Suppose the encoder maps to . The slightly changed field then lands close to , for example at , and never at .
What the plain autoencoder does not give is twofold:
No control over how big "nearby" is. Continuity only promises that small enough changes of the field give small changes of the code. How steep the encoder is, how far the code moves per unit change of the field, depends on training.
No check on the decoder between the codes. Add a second field, , with code . The midpoint of the two codes is . If no training field was ever encoded near , the loss never checked what the decoder produces there.
Fixing this takes two jobs. Training the decoder on whole regions around each code, instead of single points, fills the space. A second loss term keeps those regions from shrinking back to points.
Clouds instead of points
The encoder now outputs two numbers per code number: a centre and a spread. Together they describe a small cloud around the centre. Instead of the centre, a random point of the cloud is decoded:
(2)
Where denotes the list of centres and the list of spreads (one of each per code number), a list of fresh random numbers drawn from a standard normal distribution (centred at 0, about 95 % of draws between −2 and 2), and multiplication number by number.
$ variational autoencoder
// figure
code space
code space
Back to the 4-number field . The encoder outputs and , and this step draws :
(3)
The decoder must rebuild from . The next time this field comes up, a different picks a different point.
Over many training steps, the decoder must rebuild from everywhere in its cloud, so the whole region comes to mean "something like ". Similar fields get overlapping clouds, and in the overlap the decoder has to serve both, which forces in-between flows. That is how the space gets filled.
The widget below shows both code spaces of real trained networks. A plain autoencoder and a VAE, each with a code of 2 numbers, were trained on the same 192 snapshots: swirls turning either way, swirl pairs and shear layers, on 12×12 cells instead of 64×64 so that the networks train in seconds. Both trained decoders run in your browser, so hovering over a point decodes the code under the cursor. In the autoencoder view, move between the groups of dots. In the VAE view, move inside a cloud.
The VAE view names its parts with three symbols that the second half of this post derives: for the standard cloud drawn as dashed rings (the KL term below explains why the clouds gather there), for the cloud the encoder gives one snapshot , and for how probable each flow is given a code , highest for the decoded flow .
$ hover between the dots. what does z decode to?
D(z): the decoder's output
most similar real flow
● ccw swirl○ cw swirl▲ swirl pair■ shear layer▒ D(z) close to a real flow▒ hole
loading two trained decoders…
p(z)prior
p(z)none: nothing says which codes are valid
E(u)encoder
E(u)the one exact code of snapshot u, with no cloud around it
D(z)decoder
D(z)the one flow the decoder builds from z; no probabilities, right or wrong
scroll to zoom · drag to pan · double-click to zoom outpinch to zoom · double-tap to zoom out
Backpropagating through a random draw
The encoder learns and only if the loss sends gradients back to them through the random draw. The direct way to draw does not:
// python
mu, sigma = encode(u)dist = Normal(mu, sigma)z = dist.sample() # detached: no gradient reaches mu and sigma
PyTorch returns sample() as a detached number, a constant with no record of where it came from, so backpropagation stops there and the encoder never learns.
The reparameterization trick writes the draw as Equation (2) instead:
// python
mu, sigma = encode(u)eps = torch.randn_like(sigma) # standard normal, no gradient neededz = mu + sigma * eps
The randomness now sits only in eps, which needs no gradient. mu and sigma enter only through a multiplication and an addition, and Post 15's rule applies: backpropagation works whenever every operation has a local derivative. Alternatively, dist.rsample() does exactly this internally.
Why the clouds shrink
Which way does the reconstruction loss push the centre and the spread ?
Take one code number with and , so , and assume the decoder rebuilds best from exactly :
(4)
Where denotes the sampled code number. The loss reaches and only through , so by the chain rule (Post 15):
(5)
The first factor for both partial derivatives is positive if landed above 3 and negative if below. The second is how much moves when or grows.
Step 1. gives : , . Both go down.
Step 2. gives : , . goes up, goes down again.
The pushes on simply converge towards their average and cancel out. The push on however, is positive for every draw: a bigger always moves further from 3, and further from 3 rebuilds worse. Every draw says: shrink.
The reconstruction loss therefore does two things. For the decoder, the random points teach it to rebuild from anywhere in the cloud, which fills the space. For the encoder, it shrinks toward 0, a single point. Left alone, the VAE turns back into a plain autoencoder.
The KL term
To stop the clouds from shrinking into points, a second loss term pulls every cloud toward one fixed standard cloud with centre 0 and spread 1, the same standard normal distribution that is drawn from. Per code number it reads:
(6)
Where and denote the centre and spread the encoder outputs for this code number, and the natural logarithm. The name KL is explained in the second half.
At , it gives , and only there. The part punishes a centre far from 0. The rest, , punishes a wrong spread. With :
: KL = 0
:
:
As , grows without limit, so shrinking a cloud to a point becomes infinitely expensive.
$ kl divergence
// figure
each z's share of the KL−3−2−10123
each z's share of the KL−3−2−10123
The total loss adds this term for every code number to the reconstruction loss:
(7)
Where denotes the reconstruction loss of Equation (1), computed from the sampled code of Equation (2), Equation (6) for code number , summed over all 1,024 code numbers (the code dimension), and a weight chosen by hand.
The two terms pull in opposite directions. Reconstruction wants small, separated clouds, because each then decodes precisely. KL wants large clouds centred on 0, which overlap. Training settles in between: clouds small enough to rebuild well, and large enough to overlap and fill the space.
What the filled code space gives
Back to snapshot A (swirl on the left, code ) and snapshot B (same swirl slightly further right, code ). Walk from to in small steps and decode each step. In a trained VAE, the swirl slides gradually from left to right, and nothing breaks on the way.
The filled code space has three properties:
Nearby codes decode to similar flows.
Small moves in the code give small changes in the flow.
Every region decodes to something that looks like water, because the KL term packed all clouds around the standard cloud, and together they cover it.
This allows two uses:
Generate. Draw a random point from the standard cloud and decode it. The result is a new, realistic flow that was never in the training data.
Predict. Encode the current snapshot, move its code to where the next snapshot's code should be, and decode.
These two loss terms, reconstruction and KL, are called the evidence lower bound (ELBO) in the literature that the VAE is being optimized for. The second half of this post derives where it comes from and why it is built the way it is.
The goal: a model that produces realistic flows
The VAE is meant to be used as a generative model: a model that can be run again and again, where every run returns one new snapshot . Two runs return two different snapshots. What we want from it is a high chance of a realistic flow in every run, like the snapshots in the training data, and a low chance of noise.
"High chance" becomes a number by counting. Run the model times and look where the outputs land. A snapshot is a list of 8,192 real numbers, so no two runs return exactly the same one. Instead, count the runs that land in a small window around a snapshot :
(8)
Where denotes the density of the model at the snapshot , and the number of runs. For a single number, the size of the window is its width. For 8,192 numbers, it is the volume of a small box around . The approximation becomes exact as grows without limit and the window shrinks onto . Dividing by turns the count into a share of all runs. Dividing by the size of the window makes the result independent of how big a window we picked.
An example with a single number: runs, a window of width 0.01, and 3,000 runs land in it. Then . A window of width 0.02 catches about 6,000 runs and gives the same 0.3.
Every run lands somewhere, so the area under over all snapshots is always exactly 1. Raising at one snapshot therefore lowers it somewhere else.
Machine learning texts write the data as and its density as . This post keeps the snapshot .
An untrained model spreads its density thinly over every u, so most of its runs return noise. A trained model should pile its density onto the realistic flows. We do not have all realistic flows, only training snapshots , which are samples of them. The training goal is therefore: make as large as possible for every training snapshot.
$ move along u, then run both models
// p(u)
━ model density p(u)▲ training snapshot, ▮ realistic flowssame vertical scale · area under each curve = 1 · illustration: one axis stands for 8,192 numbers
realistic
p_init(u) here
1.28
p_opt(u) here
9.07
realistic runs · untrained
–
realistic runs · trained
–
Equation (8) needs millions of runs to evaluate the density at a single snapshot, far too many for training. Training needs a formula that computes from the model itself. Building that formula is the next step, and it is where the trouble starts.
How the model produces a snapshot
A formula for needs the exact steps of one run.
Why the model needs a code
Without a code, the model would draw each of the 8,192 numbers of a snapshot independently of the others. But the numbers of a realistic flow are not independent: all of them follow from a few shared numbers, for one swirl the four numbers centre x, centre y, size and spin speed.
So the model draws only the few shared numbers at random, the code (1,024 numbers in our VAE), and computes all 8,192 numbers from them with a fixed function, the decoder . All 8,192 numbers then come from the same draw, so they fit together. Papers call the code the latent variable. Latent means hidden: a training snapshot comes without its code.
Why the code is drawn at random
The decoder is a fixed function: the same code always gives the same snapshot. A generative model must return a new snapshot in every run, so every run needs a new code. Taking the code of an existing snapshot does not help: decoding it gives back that snapshot, not a new one. So every run draws its code at random, from a distribution that is chosen once, before training. Its density is written .
Why a normal distribution
Two facts make the choice of free.
A function can turn one distribution into another. Draw a number from a standard normal distribution, put it into a function , and keep the result . Repeated many times, the values pile up into a new distribution, and its shape is set by . Where is steep, neighbouring values are pulled far apart, so few values land there. Where is flat, many values are squeezed onto nearly the same , so many land there. The function "two positions" below, for example, turns the single bell into two peaks, like a swirl that sits either on the left or on the right.
$ push normal draws through a function
// transform
● z ~ standard normal (never changes)━ function x = 0.5 + 0.3·tanh(3z)▮ where the x values land
last draw z
–
its x = f(z)
–
draws pushed through
0
For every target distribution we care about, some function turns standard normal draws into draws from it.
A neural network can approximate any continuous function. This is the universal approximation theorem: a network with enough neurons comes as close as we want to any continuous function on a bounded range of inputs by adding up different neuron-outputs that each went through some non-linear activation function. The theorem only says such a network exists. Whether training finds it is a separate question.
Together: whatever distribution the codes come from, some function turns them into realistic flows, and the decoder can approximate that function. So the choice of does not limit which flows the model can produce, and we pick the most convenient one, the standard normal distribution with centre 0 and spread 1. It is easy to sample (torch.randn), and the encoder's clouds are normal distributions too, so the KL term between a cloud and it has the short formula of Equation (6). We therefore sample as:
(9)
From a fixed output to a density
Fix the code . Every run with this code returns the same snapshot . Take one number, for which the decoder outputs 0.80 m/s. Runs with this code never return 0.81 m/s or 5.0 m/s, so for this code the density at both values is 0: it cannot tell a near miss from a far one. Training needs a density for a fixed code that grows the closer comes to the training snapshot.
So we assume, on paper, that a run returns plus a small random error in every number:
(10)
Where denotes the decoder's output (8,192 numbers), 8,192 numbers, each drawn independently from a standard normal distribution, and the spread of the error, a small fixed number we choose, for example 0.01 m/s.
Keep in mind that equation (10) does not describe a single snapshot. It describes every snapshot a run could return for this code, and how often.
A run still never lands exactly on a training snapshot, and it does not need to: Equation (8) counts the runs that land in a small window. Take one number with decoder output 0.80 m/s, a training value of 0.81 m/s, and a window from 0.805 to 0.815 m/s. Without the error, all of 1,000,000 runs land exactly on 0.80 m/s and none in the window, so the density is 0. With the error and m/s, about 241,700 runs land in the window, so the density is . Moving the decoder output closer to 0.81 m/s catches more runs, and moving it away catches fewer.
With the code fixed, the only randomness left is , so each number of follows a normal distribution centred on the same number of , with spread . This density of for a fixed code is written , read "p of u given z". Unlike , which has a peak on every realistic flow, is one narrow bump around : high for snapshots close to the decoder's output, practically 0 for snapshots far from it.
$ drag the code z
// p(u | z)
━ p(u | z): where runs with this code land▲ training snapshotarea under the bump = 1 · illustration: hand-made decoder, one axis stands for 8,192 numbers
code z
−0.60
spread s
0.025
p(u | z) at training snapshot
≈ 0
A run therefore has two steps, each with a known density. Step 1 draws the code, with density . Step 2 turns the code into a snapshot, with density . The training goal needs , the density of the snapshot after both steps. The next section computes it from these two.
The density of a snapshot after both steps
A run can reach from any code. So adds up, over all codes, how likely the code is times how likely that code ends at :
(11)
Where the sum runs over all codes. With two codes, each drawn in half of the runs, where lands near in 8 % of its runs and in 2 %: .
The same example as a table: one row per code, one column per snapshot (here only and one column for all other snapshots together), and in each cell the share of all runs that draw this code and land there.
near
elsewhere
row total
0.5 · 0.08 = 0.04
0.46
0.50
0.5 · 0.02 = 0.01
0.49
0.50
column total
0.05
0.95
1
A cell holds the joint density: how likely a run is to draw and end at . A row total is how often that code is drawn, . The column total under is , written in the table's margin. That is why it is called the marginal density. is called the prior: what we know about the code before seeing any snapshot. is called the likelihood: how well the code explains .
The code numbers are continuous, so the sum becomes an integral:
(12)
Where denotes the size of a tiny box of codes, and the integral adds up all boxes.
This integral cannot be computed in practice: it needs a decoder run for every code, and even with only 10 values for each of the 1,024 code numbers, that is runs for a single training snapshot.
The codes that could have produced a snapshot
Almost every term of Equation (12) is practically 0. A code whose decoded flow has its swirl on the right practically never produces a snapshot with the swirl on the left, because the small error of Equation (10) cannot move a whole swirl. So for a given snapshot , only the few codes whose is close to contribute. If we knew which codes these are, the decoder would only have to run on them.
The posterior
We have observed the snapshot and want to know which code produced it. The answer comes from counting runs in the two-code example. Run the model 1,000 times. The code is drawn in half of the runs, so 500 times, and 8 % of these 500 runs, which is 40 runs, land near . The code is also drawn 500 times, and 2 % of these runs, which is 10 runs, land near . This is the table of the previous section with every share multiplied by the 1,000 runs:
near
elsewhere
row total
40
460
500
10
490
500
column total
50
950
1,000
Because we observed , only the 50 runs in the column "near " can be the run that produced it. The other 950 runs landed somewhere else, so they are ruled out. Of the 50 remaining runs, 40 started with and 10 started with . The share of among them is therefore 40 / 50 = 0.8, and the share of is 10 / 50 = 0.2. The two shares add up to 1, because each of the 50 runs started with exactly one of the two codes.
This share is written , read "p of z given u", and called the posterior, Latin for "coming after": how likely each code is after seeing . The prior , Latin for "coming before", is how likely each code is before seeing any snapshot, here 0.5 for each code. Seeing raises from 0.5 to 0.8, because lands near four times as often as (8 % against 2 %).
Bayes' rule
The cell of in the column "near ", 40 of 1,000 runs or 0.04, can be computed in two ways. Going along its row: is drawn in 0.5 of all runs, and 0.08 of these runs land near , so the cell is . Going along its column: 0.05 of all runs land near , and 0.8 of these runs started with , so the cell is . Both ways count the same 40 runs, so the two products are equal, and both equal the joint density :
(13)
Where denotes the prior, the likelihood, the joint density, the marginal and the posterior. Dividing both ends by gives Bayes' rule:
(14)
Where the symbols are as in Equation (13). In words: the likelihood is a cell divided by its row total, the posterior is the same cell divided by its column total. Check: .
$ each dot is one run of the model
// bayes' rule
Each dot is one run of the model. Step 1 of a run draws a code: zA in 50 of 100 runs, zB in 50. A row's share of all runs is the prior p(z).
prior p(zA)
50/100 = 0.50
prior p(zB)
50/100 = 0.50
illustration: two codes, three snapshots, made-up numbers
The numerator is cheap: is the standard normal density, and needs one decoder run. The denominator is the integral of Equation (12), the very thing we cannot compute. So the posterior cannot be computed either.
The encoder's guess
Instead of computing the posterior , the encoder guesses it. For a snapshot , the encoder outputs a centre and a spread for each of the 1,024 code numbers: the cloud of Equation (2). This cloud is the encoder's guess of which codes could have produced . It is written , where the letter marks it as a guess of the true posterior . Papers call it the approximate posterior.
For each code number, the guess can only be a single normal bump, because the encoder outputs just two numbers for it, and . The true posterior can have any shape. Take one code number and suppose that the codes −2 and +2 both decode to a flow close to , while the codes around 0 do not. Then the true posterior has two peaks, one at −2 and one at +2, with almost nothing in between. A single bump cannot match this. With centre −2 and a small spread, it covers one peak and misses the other. With centre 0 and a large spread, it covers both peaks, but it also puts much of its weight on the codes around 0, which do not produce . So the guess is in general only approximately right, and training chooses the and that make it as close as possible.
The widget below shows both distributions for a single code number and a hand-made decoder that turns two different codes into the same snapshot.
$ drag u up or down, drag the guess sideways
// posterior vs guess
━ p(z | u): true posterior (Bayes' rule)━ q(z | u): the encoder's guess, one normal bump┄ prior p(z)illustration: one code number, hand-made decoder
observed snapshot u
0.30
peaks of p(z | u)
2
guess centre μ
0.00
guess spread σ
1.00
best bump: the μ and σ closest to p(z | u), measured with the KL divergence of the next section
The guess is a density function of the code: it gives every code a density. Choosing the best density function out of a family of allowed ones, here all normal bumps, is called variational inference. "Variational" comes from the calculus of variations, the area of mathematics about choosing the best function. "Inference" is the statistics word for answering a question backwards. The model runs forwards, from a code to a snapshot. Inference asks the reverse: for a snapshot we have observed, which codes produced it? The posterior is the answer to exactly this question, so guessing it is inference. In the VAE, every allowed function is fixed by its and .
This leaves a contradiction. Training should bring as close as possible to , but cannot be computed. The next sections show how training gets around this without ever computing , and why the KL term of the first half compares the guess with the prior instead.
How far the guess is from the posterior
The measure for how far the guess is from the posterior is a weighted average, the same kind of average as the average roll of a loaded die.
Take a die that shows a 6 with probability 0.5 and each other face with probability 0.1. Its average roll is every face times how often it comes up, added up: . This weighted average is called the expectation:
(15)
Where denotes the possible outcomes (the faces), how often outcome comes up, and the value of outcome (the number on the face).
The Kullback–Leibler divergence, KL for short, is exactly this average. The outcomes are the codes, the guess says how often each code comes up, and the value of each code is the mismatch :
(16)
Where the sum runs over all codes. The mismatch is 0 where the guess and the posterior give a code the same probability, because then the ratio is 1 and . It is positive where the guess gives a code more than the posterior does, and negative where it gives less.
The KL is never negative (Gibbs' inequality, not proved here), and it is 0 only when the guess and the posterior are equal. Swapping and gives a different number (0.19 instead of 0.22 for the first guess ), so it is called a divergence and not a distance.
For continuous codes, the sum becomes an integral:
(17)
Where denotes the average of the bracket over codes drawn from the guess . So the KL divergence is the average of the mismatch over all codes , where the mismatch at each code is weighted by the guess's density at that code, .
The widget below adds up Equation (16) one term at a time, for a posterior with two peaks and a guess that you can move.
$ press "next term", point at a bin, drag q sideways
Equation (6) of the first half is this same measure for one code number, with the prior in place of the posterior . Training should make Equation (17) small, but it contains the posterior , which cannot be computed. The next section shows how to make it small anyway.
The evidence lower bound
The way around is to take Equation (17) apart with Bayes' rule. Its pieces then rearrange into a formula for , the quantity the training goal asks to make large.
Step 1: switch to the logarithm.Equation (17) contains a logarithm, so the derivation works with instead of . The goal stays the same: grows whenever its input grows, so the weights that make largest also make largest. Taking the logarithm of Bayes' rule, Equation (14):
(18)
Step 2: replace the posterior from the KL. The bracket of Equation (17) equals . The posterior sits in , so we replace that term with the right side of Equation (18):
(19)
Where denotes, as in Equation (17), the average over codes drawn from the guess.
Step 3: average the four terms one by one.Equation (15) multiplies every value by its weight and adds up, so the average of a sum is the sum of the averages. Two of the four terms then simplify:
does not depend on the code: for a given snapshot it is one fixed number. The average of a fixed number is that number, because the weights add up to 1.
, and its average over the guess is Equation (17) with the prior in place of the posterior: the KL divergence between the guess and the prior.
(20)
Where denotes the KL divergence between the guess and the prior, and the other symbols are as above.
Step 4: solve for the marginal. Adding the likelihood term and subtracting the KL to the prior on both sides of Equation (20) leaves alone on one side:
(21)
Where the symbols are as in Equation (20). The three terms on the right:
, the reconstruction term. For each code , scores how well that code explains the snapshot: high if the decoded flow is close to , strongly negative if it is far. The guess decides how much each score counts. If the encoder puts much weight on a code that decodes to something unlike , a strongly negative score counts fully and pulls the term down. If it puts almost no weight on that code, the bad score barely counts. The term is therefore high when the encoder puts its weight only on codes that decode close to .
, the prior term: how far the guess is from the prior. It is subtracted, so a guess far from the standard cloud lowers the right side.
, the gap: how far the guess is from the posterior. It is the one term that still contains the posterior.
Step 5: drop the gap. The gap is a KL divergence, so it is never negative. Dropping it can only make the right side smaller:
(22)
Where the symbols are as in Equation (21). The marginal is also called the evidence: how well the model explains the observed snapshot. The right side never exceeds the logarithm of the evidence, hence its name, the evidence lower bound. Both sides are equal exactly when the gap is 0, which means when the guess equals the posterior. Therefore, we do not have to optimize for the evidence directly, which is impossible, but for the ELBO, which is computable. It's like probably never reaching the ceiling, but still being able to raise the floor as high as possible.
The ELBO is the loss of the first half
Training lowers a loss, so the VAE's loss is the negative ELBO.
The reconstruction term. By Equation (10), a run with code draws each of the 8,192 numbers independently from a normal distribution with centre and spread . The density of independent draws is the product of their single densities:
(23)
Where and denote number of the snapshot and of the decoder's output, and each factor is the bell curve of one number. The logarithm turns the product into a sum and removes the exp:
(24)
Where const contains no network weight, so it does not change training. So is the squared error of Equation (1), divided by , plus a constant.
The reconstruction term scores how well the model has captured the snapshot . For every code , it multiplies two things: , which is high if lands near and strongly negative if it lands far, and , how sure the encoder is about that code. For a code that lands far from , the encoder should give , so its strongly negative score adds almost nothing. For a code that lands near , it should give a high , so its high score adds a lot. The weights add up to 1, so the term is a weighted average of the scores. Training never computes this weighted average explicitely. Each step draws one code from the cloud with Equation (2) and gives one error signal, specific to that one draw. The draws are tied to : codes with a high weight are drawn often, codes with a low weight rarely. So the weighted average that describes is built up over many training steps, not computed in a single one.
The prior term splits into one KL divergence per code number, and each is Equation (6).
Putting both terms together, with the factor pulled out in front:
(25)
Where denotes the one sampled code and Equation (6) for code number . The bracket is exactly the loss of Equation (7) with . The factor in front multiplies the whole loss by one fixed positive number, which does not change which weights make it smallest, so it can be dropped. The KL weight of Equation (7) is therefore the error spread that we chose freely in Equation (10), in another form.
One training step on one snapshot:
// python
mu, sigma = encode(u)z = mu + sigma * torch.randn_like(sigma) # Equation (2): one code from the cloudrec = ((decode(z) - u) ** 2).sum() # Equation (1): squared error over the 8,192 numberskl = (0.5 * (mu**2 + sigma**2 - 1 - torch.log(sigma**2))).sum() # Equation (6), summed over the 1,024 code numbersbeta = 2 * s**2 # s from Equation (10), or set beta directlyloss = rec + beta * kl # Equation (7) = 2s² · (−ELBO), up to a constantloss.backward()