Course contents 06 / 34

06 / 34 · Foundations

Autoencoders

A network trained to reproduce its input through a narrow code: a convolutional autoencoder on MNIST, its reconstruction loss, denoising and sparse variants, and why its codes do not yet give a way to generate.

On this page 7

A digit written by hand and resized to 64×6464 \times 64 is 4096 numbers, yet almost all of them are predictable from a few facts: which digit it is, how thick the stroke is, how it slants. Can a network find such a short description on its own, without labels? Train it to reproduce its input after squeezing it through a layer of 512 numbers. The copy is only the pretext. What we want is the code the network is forced to build on the way, and later, a way to make new digits from codes (Hinton and Salakhutdinov, 2006; Goodfellow, Bengio and Courville, 2016, chapter 14).

Such a network is an autoencoder. Training a network to pass its input through a narrow hidden layer and back already appears as the “encoding problem” of Rumelhart, Hinton and Williams (1986). It uses the convolution, batch-norm and LeakyReLU blocks of the previous note.

Architecture: downsample, bottleneck, upsample#

An encoder fφf_\varphi with parameters φ\varphi maps an image xx to a latent code zz, and a decoder gθg_\theta with parameters θ\theta maps the code back to a reconstruction x^\hat x:

z=fφ(x),x^=gθ(z).\begin{aligned} z &= f_\varphi(x), \\ \hat{x} &= g_\theta(z) . \end{aligned}

The letters follow the VAE: φ\varphi belongs to the encoder and θ\theta to the decoder. The code is smaller than the input, so the network cannot pass the pixels through unchanged; it must keep what it needs to rebuild the image and drop the rest. Every image becomes a point in a learned, lower-dimensional latent space.

With a linear encoder and decoder and squared error, the best the network can do is project onto the top principal components: a linear autoencoder learns the PCA subspace (autoencoders as nonlinear PCA). Nonlinear layers let the code follow curved structure that PCA cannot.

The MNIST digits are resized from 28×2828 \times 28 to 64×6464 \times 64, with pixel values in [0,1][0, 1]. The encoder halves the side four times with stride-2 convolutions, 64→32→16→8→464 \to 32 \to 16 \to 8 \to 4 (the output-size formula), and the decoder doubles it four times. A side divisible by 24=162^4 = 16 makes the mirrored decoder return to the input size. At 28 the encoder would give 28→14→7→4→228 \to 14 \to 7 \to 4 \to 2, and four doublings would end at 32.

Figure

The convolutional autoencoder, layer by layer

Autoencoder pipeline with tensor shapesA row of eleven tensors from left to right. Input x of shape 1 by 64 by 64; after stride-2 convolutions 16 by 32 by 32, 32 by 16 by 16, 32 by 8 by 8 and 32 by 4 by 4; after a plain 3 by 3 convolution the bottleneck z of shape 32 by 4 by 4, which is 512 numbers. The decoder then upsamples by two and convolves four times: 32 by 8 by 8, 32 by 16 by 16, 32 by 32 by 32, 16 by 64 by 64, and a final convolution with a sigmoid gives the reconstruction x hat of shape 1 by 64 by 64. A red arrow from x hat back to x is labelled MSE: compare output with input.encoder fφ: downsamplelearned filters, stride 2decoder gθ: upsamplebilinear ×2, then convs2s2s2s2conv×2×2×2×2out64×641 ch32×3216 ch16×1632 ch8×832 ch4×432 ch4×432 ch8×832 ch16×1632 ch32×3232 ch64×6416 ch64×641 chxx̂z: 32×4×4 = 512MSE(x̂, x): compare output with inputs2: conv 3×3, stride 2 → BN → LeakyReLU(0.2) · conv: conv 3×3, stride 1×2: bilinear upsample ×2 → conv 3×3 → BN → LeakyReLU(0.2) · out: conv 3×3 → sigmoidAutoencoder pipeline with tensor shapesTensors stacked from top to bottom. Encoder: x of shape 1 by 64 by 64, then 16 by 32 by 32, 32 by 16 by 16, 32 by 8 by 8, 32 by 4 by 4 after stride-2 convolutions, and the code z of shape 32 by 4 by 4, 512 numbers, after a 3 by 3 convolution. Decoder: upsample by two and convolve to 32 by 8 by 8, 32 by 16 by 16, 32 by 32 by 32, 16 by 64 by 64, and a final convolution with sigmoid gives x hat of shape 1 by 64 by 64. A red arrow on the left runs from x hat back up to x, labelled MSE.encoder fφ: downsamplelearned filters, stride 2decoder gθ:upsample + convs2s2s2s2conv×2×2×2×2out1×64×6416×32×3232×16×1632×8×832×4×432×4×432×8×832×16×1632×32×3216×64×641×64×64xx̂z= 512MSE(x̂, x)s2: conv 3×3, stride 2 → BN → LeakyReLU×2: bilinear ×2 → conv 3×3 → BN → LeakyReLUconv: conv 3×3, stride 1out: conv 3×3 → sigmoid
Each bar is one tensor: its length grows with the spatial size (log scale) and its thickness with the number of channels. Four stride-2 blocks and a 3×3 convolution take the 64×64 input to the code z of 32×4×4 = 512 numbers; four upsample-and-convolve blocks and a sigmoid output bring it back to 64×64.

Every encoder block is a 3×33 \times 3 convolution with stride 2, batch norm and LeakyReLU with slope 0.2; a last stride-1 convolution produces the code. Every decoder block upsamples by 2 with bilinear interpolation and then applies a 3×33 \times 3 convolution, batch norm and LeakyReLU. A final convolution maps 16 channels to 1, followed by a sigmoid.

TensorShape (channels × height × width)Numbers
input xx1×64×641 \times 64 \times 6440964096
encoder blocks 1, 2, 316×32216 \times 32^2, 32×16232 \times 16^2, 32×8232 \times 8^21638416384, 81928192, 20482048
code zz after block 4 and the last convolution32×4×432 \times 4 \times 4512512
decoder blocks 1, 2, 332×8232 \times 8^2, 32×16232 \times 16^2, 32×32232 \times 32^220482048, 81928192, 3276832768
decoder block 416×64×6416 \times 64 \times 646553665536
output x^\hat x1×64×641 \times 64 \times 6440964096

The code holds 512 numbers: 8 times fewer than the resized image, but only 1.5 times fewer than the original 784 pixels. The compression is mild. What matters is how the code is organized.

How to read the encoder and decoder#

No layer is told to compress. The first encoder block even expands 4096 values to 16384 activations; the code becomes small only because the shapes narrow toward the bottleneck. Each halving is a learned stride-2 convolution, so the network decides what survives it, where max or average pooling would apply a fixed rule. In image classifiers, replacing max pooling by a stride-2 convolution cost no accuracy (Springenberg et al., 2015).

The decoder is not an upscaler. Bilinear upsampling has no parameters; the learned convolution after it fills in the detail. In trained convolutional classifiers, early layers respond to edges and deeper layers, whose receptive fields are larger, to parts (Zeiler and Fergus). The same growth of receptive fields lets these channels encode stroke fragments and larger parts of a digit; this run did not visualize them.

Reconstruction loss#

The standard loss is the mean squared error between output and input, averaged over the nn values of a batch:

MSE(x^,x)=1n∑i=1n(xi−x^i)2.\mathrm{MSE}(\hat x, x) = \frac{1}{n}\sum_{i=1}^{n} \left(x_i - \hat{x}_i\right)^2 .

PyTorch’s nn.MSELoss() averages over every pixel of the batch: n=64⋅64⋅64=262144n = 64 \cdot 64 \cdot 64 = 262144 for 64 images. Since pixels lie in [0,1][0, 1], binary cross-entropy is the natural alternative:

BCE(x^,x)=−1n∑i=1n[xilog⁡x^i+(1−xi)log⁡(1−x^i)].\begin{aligned} \mathrm{BCE}(\hat x, x) = -\frac{1}{n}\sum_{i=1}^{n}\Big[ &x_i \log \hat x_i \\ &+ (1 - x_i)\log(1 - \hat x_i)\Big] . \end{aligned}

Each loss is a negative log-likelihood. A Gaussian decoder with fixed variance s2s^2 on DD pixels has the density (2πs2)−D/2exp⁡(−∥x−x^∥2/(2s2))(2\pi s^2)^{-D/2} \exp\big(-\lVert x - \hat x\rVert^2/(2s^2)\big); taking minus its logarithm,

−log⁡N(x; x^, s2I)=∥x−x^∥22s2+D2log⁡(2πs2),-\log \mathcal N\big(x;\, \hat x,\, s^2 I\big) = \frac{\lVert x - \hat x\rVert^2}{2s^2} + \frac D2 \log(2\pi s^2),

so MSE is the Gaussian negative log-likelihood up to a positive factor and a constant. BCE is the negative log-likelihood of independent Bernoulli pixels with means x^i\hat x_i. That reading holds only for binary pixels. The resized digits have many grey values. For those BCE is still minimized at x^i=xi\hat x_i = x_i: its derivative in x^i\hat x_i, −xi/x^i+(1−xi)/(1−x^i)-x_i/\hat x_i + (1 - x_i)/(1 - \hat x_i), vanishes there. But it is no longer the log of a normalized density on [0,1][0, 1]: for x^i=0.9\hat x_i = 0.9, ∫010.9x 0.11−x dx=0.8/ln⁡9=0.364\int_0^1 0.9^{x}\, 0.1^{1-x}\, dx = 0.8/\ln 9 = 0.364, not 1 (Loaiza-Ganem and Cunningham, 2019). The VAE builds on this reading of the loss as a likelihood.

Two practical traps follow. With a sigmoid already applied in forward, BCE must be nn.BCELoss: nn.BCEWithLogitsLoss applies its own sigmoid, and the pair would apply it twice. The stabler option is to drop the sigmoid and pass logits to BCEWithLogitsLoss. And the input range must suit the output: colour images are often mapped to [−1,1][-1, 1] by x↦2x−1x \mapsto 2x - 1, which rules out a sigmoid output and BCE, whose targets must lie in [0,1][0, 1].

Emergent structure#

Nothing in the loss asks for an organized latent space, and no labels are used. Still, structure emerges. A t-SNE projection (van der Maaten and Hinton, 2008) of the 512-dimensional codes of the test set, coloured by digit, shows clusters by class that are cleaner than before training. Most digits form one compact cluster; the 2s split into two groups and the 1s form an elongated band.

t-SNE draws neighbourhoods. It keeps each code’s nearest neighbours near it in the plane, with the perplexity, 30 here, setting roughly how many count. Cluster sizes and the gaps between clusters carry little information (Wattenberg, Viégas and Johnson, 2016; reading t-SNE). The plot shows whether a code’s neighbours share its label, and even that only qualitatively.

A number comes from a probe: freeze the encoder, compute the codes of labelled images, train a simple classifier on them and report its accuracy on held-out images (Alain and Bengio, 2016; the linear probe of the Deep Learning course). The classifier sees only the code, so its accuracy measures how much class information the code keeps in an easily readable form. The fair baseline is the same probe on an untrained encoder of the same architecture. The same codes can also replace Inception features in FID when the images are unlike ImageNet.

Why the codes do not generate#

Two experiments ask whether the latent space can be used to make images.

Interpolation encodes a 7 and a 2 and decodes zα=(1−α)z1+αz2z_\alpha = (1 - \alpha) z_1 + \alpha z_2 for eight values of α\alpha from 0 to 1. The endpoints are clean digits; the middle frames are overlays of the two strokes, not digits morphing into each other.

Sampling fits an axis-aligned Gaussian to the training codes of each digit, using the per-coordinate mean and standard deviation, draws one code per class and decodes it. In the saved run six of the ten samples are recognisable; the 2, 4, 5 and 8 are badly distorted.

Both failures have the same cause. Training asks only that the codes of training images decode back to those images. It says nothing about where in R512\mathbb R^{512} the codes sit or what lies between them, so an arbitrary point can decode to anything. The codes follow no distribution we know how to sample from: the diagonal Gaussians ignore correlations between coordinates, and they needed labels. A plain autoencoder learns a representation; it is not yet a generative model. The variational autoencoder closes this gap by making the distribution of codes part of the training objective.

Variants#

Denoising autoencoder#

A denoising autoencoder (Vincent et al., 2008) changes the task and keeps the architecture. It corrupts the input with a random q(x~∣x)q(\tilde x \mid x), reconstructs from the corrupted version, x^=gθ(fφ(x~))\hat x = g_\theta(f_\varphi(\tilde x)), and compares the result with the clean xx. The original paper zeroes a random fraction of the input; additive Gaussian noise is the other common choice (Vincent et al., 2010). Copying the input no longer works, so the network must learn which structure is signal and which is noise.

Figure

Denoising autoencoder: corrupt the input, score against the clean image

Denoising autoencoder training stepLeft to right: a clean digit image x; an arrow labelled add noise, x tilde equals x plus 0.2 epsilon with epsilon standard normal, leading to the speckled noisy image x tilde; an arrow into an hourglass-shaped autoencoder, encoder f phi, code z, decoder g theta, with dropout in every block; an arrow out to the smooth reconstruction x hat. A red arrow below runs from x hat back to the clean x, labelled MSE of x hat and x, the target is the clean image, not x tilde.xclean imagex̃corrupted inputx̂reconstructionadd noisex̃ = x + 0.2·εε ~ N(0, I)fφzgθDropout2d(0.3) after every blockloss = MSE(x̂, x): target is the clean x, not x̃Denoising autoencoder training stepTop to bottom: the clean digit x; an arrow labelled add noise, x tilde equals x plus 0.2 epsilon; the noisy image x tilde; an hourglass autoencoder f phi, z, g theta with dropout in every block; the reconstruction x hat. A red arrow on the left runs from x hat back up to the clean x, labelled MSE of x hat and x.xcleanx̃corruptedx̂reconstructionadd noisex̃ = x + 0.2·ε, ε ~ N(0, I)fφzgθDropout2d(0.3)loss = MSE(x̂, x) against the clean x
The network sees only the corrupted input, but the loss compares its output with the clean image, so copying the input is penalised. The pixel images are a computed toy digit with Gaussian noise of standard deviation 0.2 and no clipping.

Here the corruption is x~=x+0.2 ε\tilde x = x + 0.2\,\varepsilon with ε∼N(0,I)\varepsilon \sim \mathcal N(0, I), without clipping, and every block also applies Dropout2d(0.3), which drops whole feature maps during training. After 5 epochs the training loss is 0.01020.0102 against the plain model’s 0.00210.0021. The task is harder, so the numbers are not directly comparable. On noisy test digits the model removes the noise completely, with slightly thicker strokes and lost small details such as a short hook at the top of a 0. Its codes cluster like the plain model’s.

The idea returns later in the course. With Gaussian corruption, training a denoiser is equivalent to score matching on a smoothed data density (Vincent, 2011; derived in the score-matching note), and a diffusion model’s noise-prediction objective trains one denoiser for many noise levels.

Sparse autoencoder#

A sparse autoencoder adds a penalty that makes each hidden unit active for only a small fraction of inputs (Ng, 2011). The hidden layer can then be large, even larger than the input, without the network simply copying. Two forms are common.

The KL penalty reads a sigmoid unit’s mean activation ρ^j\hat\rho_j over a batch as a firing rate and compares it with a target rate ρ\rho through the KL divergence between two coins:

L=MSE(x^,x)+β∑jDKL(ρ ∥ ρ^j),DKL(ρ ∥ ρ^j)=ρlog⁡ρρ^j+(1−ρ)log⁡1−ρ1−ρ^j,\begin{aligned} \mathcal L &= \mathrm{MSE}(\hat x, x) + \beta \sum_{j} D_{\mathrm{KL}}(\rho \,\|\, \hat\rho_j), \\ D_{\mathrm{KL}}(\rho \,\|\, \hat\rho_j) &= \rho \log\frac{\rho}{\hat\rho_j} + (1-\rho)\log\frac{1-\rho}{1-\hat\rho_j} , \end{aligned}

with ρ=0.05\rho = 0.05 and β=0.001\beta = 0.001 here. Ng (2011) averages over the training set; the batch mean estimates it. The penalty fixes only each unit’s average rate, which a unit firing weakly at 0.05 for every input also satisfies; sparsity per input has to come from the interplay with the reconstruction loss. This model’s decoder uses transposed convolutions with kernel 4, stride 2 and padding 1, which double the side: the output size (H−1) s−2p+(k−1)+1(H - 1)\,s - 2p + (k - 1) + 1 becomes (H−1)⋅2−2+4=2H(H - 1) \cdot 2 - 2 + 4 = 2H.

Figure

Dense and sparse codes: what the sparsity penalty aims for

Dense versus sparse activationsTwo bar charts of 16 unit activations between 0 and 1. In the dense code almost every bar is around 0.5. In the sparse code one bar is high, about 0.7, and all other bars are close to zero. A note below says the KL penalty is beta times the sum over units of KL between rho and the average activation rho hat j.dense codeevery unit partly active, around 0.500.51hidden units j = 1 … 16sparse code1 of 16 units active for this input00.51hidden units j = 1 … 16penalty: β · Σj KL(ρ ‖ ρ̂j), ρ̂j = batch mean of unit j; ρ = targetDense versus sparse activationsTwo bar charts of 16 unit activations between 0 and 1. In the dense code almost every bar is around 0.5. In the sparse code one bar is high, about 0.7, and all other bars are close to zero. A note below says the KL penalty is beta times the sum over units of KL between rho and the average activation rho hat j.dense codeevery unit partly active, around 0.500.51hidden units j = 1 … 16sparse code1 of 16 units active for this input00.51hidden units j = 1 … 16penalty: β · Σj KL(ρ ‖ ρ̂j)ρ̂j = batch mean of unit j, ρ = target
Illustrative activations of 16 sigmoid units for one input. At initialization they average about 0.5 (dense code). The KL penalty pushes each unit's average rate over a batch toward ρ = 0.05; with the reconstruction loss, each input should use a few strongly active units (sparse code). ρ is not a target for any single bar.

The L1 penalty adds λ=0.001\lambda = 0.001 times the mean absolute value of the 512 code entries:

L=MSE(x^,x)+λ512∑k=1512∣zk∣.\mathcal L = \mathrm{MSE}(\hat x, x) + \frac{\lambda}{512}\sum_{k=1}^{512} |z_k| .

Its subgradient sign⁡(zk)\operatorname{sign}(z_k) has constant size, so it keeps pulling small entries toward zero where a squared penalty’s pull vanishes. One coordinate shows the effect: minimizing 12(z−a)2+λ∣z∣\tfrac12(z - a)^2 + \lambda |z|, the subgradient condition 0∈z−a+λ ∂∣z∣0 \in z - a + \lambda\,\partial|z| gives z=sign⁡(a)max⁡(∣a∣−λ,0)z = \operatorname{sign}(a)\max(|a| - \lambda, 0), exactly zero whenever ∣a∣≤λ|a| \le \lambda (Goodfellow, Bengio and Courville, 2016, section 7.1.2). Plain gradient training steps past zero instead of landing on it, so it only drives entries close to zero.

Where the sparsity penalties break#

Neither penalty works here, for opposite reasons, and both are worth computing.

The KL penalty is too heavy. It sums over every channel and position of the four intermediate encoder layers:

16⋅322+32⋅162+32⋅82+32⋅42=27136 terms.16\cdot 32^2 + 32 \cdot 16^2 + 32 \cdot 8^2 + 32 \cdot 4^2 = 27136 \text{ terms.}

At initialization batch norm centres the sigmoids’ inputs at β=0\beta = 0, and σ(−u)=1−σ(u)\sigma(-u) = 1 - \sigma(u) puts the mean of a sigmoid of a roughly symmetric input near 0.5. With DKL(0.05 ∥ 0.5)=0.05ln⁡0.1+0.95ln⁡1.9=0.495D_{\mathrm{KL}}(0.05 \,\|\, 0.5) = 0.05 \ln 0.1 + 0.95 \ln 1.9 = 0.495, the penalty starts at about

27136⋅0.001⋅DKL(0.05 ∥ 0.5)≈13.27136 \cdot 0.001 \cdot D_{\mathrm{KL}}(0.05 \,\|\, 0.5) \approx 13 .

The plain model’s reconstruction error is 0.0020.002, nearly four orders of magnitude smaller. The logged sum of both terms falls from 8.858.85 in the first epoch to 0.2140.214 in the fifth and is still falling fast, so training has not converged; only the sum was logged, and logging the terms separately would show the split. The result is visible anyway: worse reconstructions, a fragmented t-SNE plot, and class-wise samples that are only fragments of strokes. With 27136 terms, a weight near 10−610^{-6} would start the penalty at 0.0130.013, on the scale of the reconstruction loss in the first epoch.

The L1 penalty is too light, and it can be dodged. Its loss ends at 0.00220.0022, within noise of the plain model’s 0.00210.0021, and the codes and reconstructions look the same. The first decoder block applies bilinear upsampling and a bias-free convolution, both linear, and then batch norm, which divides out the scale of its input. Replacing zz by rzr z for any r>0r > 0 leaves the decoder’s output unchanged, up to batch norm’s ε\varepsilon, and scales the penalty by rr, so the encoder can lower the penalty by shrinking zz without making it sparse. This run did not measure the scale of zz; comparing the mean of ∣zk∣\lvert z_k\rvert before and after training would show whether it happened. A sparsity penalty needs a weight tuned against the reconstruction loss and an architecture in which it cannot be bypassed.

Transposed convolution or upsample + conv?#

Both double the size. A transposed convolution learns its own upsampling filter, but when the kernel size is not divisible by the stride the kernel footprints overlap unevenly and produce checkerboard artifacts; resizing followed by a convolution avoids the uneven overlap and is the safer default (Odena, Dumoulin and Olah, 2016). Two caveats from the same study: its best results came with nearest-neighbour resizing, and bilinear resizing, which the plain model here uses, gave the authors trouble. A kernel divisible by the stride, such as 4 with stride 2 in the KL model, removes the uneven overlap: every output pixel then receives exactly k/s=2k/s = 2 taps per dimension. Learned kernels can still produce artifacts. The two decoders here differ in other ways too, so they are not a controlled comparison.

Why a sigmoid at the output?#

Inside the network the blocks use LeakyReLU, max⁡(0.2x,x)\max(0.2x, x) (Maas, Hannun and Ng, 2013), for the gradient reasons of the previous note. The output needs something else: the decoder’s last convolution is unbounded, and the targets are pixel intensities in [0,1][0, 1]. The sigmoid maps any real number into that range,

σ(x)=11+e−x,\sigma(x) = \frac{1}{1 + e^{-x}} ,

with σ(0)=12\sigma(0) = \tfrac12. In the KL-sparse model it is also the hidden activation, because the Bernoulli penalty needs activations readable as rates.

Figure

LeakyReLU and sigmoid

LeakyReLU and sigmoid activation functionsTwo plots. Left or top: LeakyReLU, a line of slope 1 for positive x and a line of slope 0.2 for negative x, meeting at the origin. Right or bottom: the sigmoid, an S-shaped curve rising from 0 to 1, passing through 0.5 at x equal to 0, with dashed asymptotes at 0 and 1.LeakyReLU(x) = max(0.2x, x)x12slope 1slope 0.2σ(x) = 1 / (1 + e⁻ˣ)x100.5 at x = 0→ 1 as x → ∞→ 0LeakyReLU and sigmoid activation functionsTwo plots. Left or top: LeakyReLU, a line of slope 1 for positive x and a line of slope 0.2 for negative x, meeting at the origin. Right or bottom: the sigmoid, an S-shaped curve rising from 0 to 1, passing through 0.5 at x equal to 0, with dashed asymptotes at 0 and 1.LeakyReLU(x) = max(0.2x, x)x12slope 1slope 0.2σ(x) = 1 / (1 + e⁻ˣ)x100.5 at x = 0→ 1 as x → ∞→ 0
LeakyReLU with slope 0.2, the activation of the convolutional blocks: the identity for positive inputs, slope 0.2 for negative ones. The sigmoid squashes every input into (0, 1), the range of pixel intensities, and equals 0.5 at x = 0; every model here puts it on the decoder output.

For targets in [−1,1][-1, 1] the sigmoid can never produce a negative value. The usual output is then

tanh⁡(x)=2 σ(2x)−1,\tanh(x) = 2\,\sigma(2x) - 1 ,

a sigmoid stretched to (−1,1)(-1, 1) (multiply the numerator and denominator of tanh⁡x=(ex−e−x)/(ex+e−x)\tanh x = (e^x - e^{-x})/(e^x + e^{-x}) by e−xe^{-x} to get (1−e−2x)/(1+e−2x)=2σ(2x)−1(1 - e^{-2x})/(1 + e^{-2x}) = 2\sigma(2x) - 1), as at the end of the DCGAN generator, whose images are scaled to [−1,1][-1, 1] (Radford, Metz and Chintala, 2016, sections 3–4). With MSE a linear output also works, clipped to the valid range for display.

What you should remember#

  • An autoencoder learns z=fφ(x)z = f_\varphi(x) and x^=gθ(z)\hat x = g_\theta(z) by reconstruction; the code is the product.
  • MSE is a Gaussian negative log-likelihood, BCE a Bernoulli one, exact only for binary pixels.
  • Codes cluster by class without labels, but random encoders already cluster; compare against them with a probe.
  • Arbitrary points of the latent space decode to garbage: nothing in training says where codes lie.
  • Denoising changes the task and connects to score matching; sparsity penalties need their weight matched to the reconstruction loss.

Notebook#

The experiments follow the autoencoder notebook of the HSE-LAMBDA Deep Generative Models repository. Every training loss and plot described above comes from the run saved with the course. The counts and penalty sizes of Where the sparsity penalties break, 27,136 terms, about 13 and 0.013, are computed from the architecture.

  • Data: MNIST resized to 64×6464 \times 64, batches of 64 with drop_last=True, 937 batches per epoch.
  • The plain autoencoder of the shape table, MSE and Adam at 10−310^{-3} for 5 epochs. The notebook names the encoder fθf_\theta and the decoder gϕg_\phi, the opposite of the letters used here. Its markdown suggests BCEWithLogitsLoss as an alternative, which would apply the sigmoid twice.
  • Latent experiments: t-SNE (perplexity 30) before and after training, test reconstructions, an 8-frame interpolation and per-class diagonal-Gaussian sampling. The “before” plot runs in eval() mode, where the untrained batch norms, with running mean 0, running variance 1, γ=1\gamma = 1 and β=0\beta = 0, are identity maps up to ε\varepsilon.
  • Denoising: Gaussian noise with factor 0.2 in training and testing (the helper’s default is 0.1) and Dropout2d(0.3) in every block.
  • KL-sparse and L1-sparse models with ρ=0.05\rho = 0.05, β=0.001\beta = 0.001 and λ=0.001\lambda = 0.001. The KL model also passes its code through a sigmoid. Both training loops run the encoder a second time to get the activations for the penalty, which doubles its cost and updates batch norm’s running averages twice per step.

Saved training losses, averaged over each epoch:

ModelEpoch 12345
plain0.01030.00340.00260.00230.0021
denoising0.03130.01370.01160.01070.0102
KL-sparse (sum of both terms)8.85314.44302.33150.78770.2141
L1-sparse (sum of both terms)0.00950.00340.00280.00240.0022

Homework 1 of the same repository has no saved outputs and empty solution cells, so it documents a procedure. Its second half is described in the FID note.

  • CIFAR-10 (3×32×323 \times 32 \times 32, ten classes) mapped to [−1,1][-1, 1], so the decoder needs a tanh⁡\tanh or linear output. The student writes an encoder whose flattened code has fewer than 3072 numbers.
  • The probe: a GradientBoostingClassifier (50 trees of depth 5) trained on the codes of 5000 random training images and scored on the 10 000 validation images. The trained encoder must beat an untrained one by 5%. A new random subset is drawn at every call, which makes the comparison noisier than it needs to be.
  • Training with AdamW at its defaults for 30 epochs, with training and validation MSE plotted per epoch, the validation pass in eval() mode under torch.no_grad(), and seeds and cuDNN flags set as in the previous note. A function named eval shadows Python’s built-in.

Next#

A plain autoencoder learns useful codes but specifies no distribution over them, so it cannot sample. The next note makes the distribution of codes part of the model and trains it with a lower bound on the log-likelihood, which turns the autoencoder into a generator.

References#