A Fixed Menu of Codes

Learning to CompressMedium+20 XP+20

A Fixed Menu of Codes

An autoencoder's encoder can put a code anywhere in latent space. A vector-quantized autoencoder takes that freedom away on purpose.

It keeps a codebook: a short list of KKK fixed vectors, each the same length as a code. Every code the encoder produces is swapped for its nearest codebook entry before the decoder sees it. The decoder then only ever receives one of KKK possible vectors, and each input can be stored as a few whole numbers (which entries were picked) instead of a list of decimals. The token-style latents used by many image generators are built this way.

Nearest means the smallest Euclidean distance. For a code zzz and an entry eee, both of length ddd, compare the squared distances

∥z−e∥2=∑j=1d(zj−ej)2\lVert z - e \rVert^2 = \sum_{j=1}^{d} (z_j - e_j)^2∥z−e∥2=j=1∑d​(zj​−ej​)2

(taking the square root would not change which entry wins).

After snapping a batch, two numbers tell you whether the codebook is healthy:

  • Usage. How many codes picked each entry. An entry that nobody picks is dead weight: the decoder never learns what it means.
  • Snapping error. How far the codes had to move: the squared gap between each code and its chosen entry, averaged over every number in the batch. It is the same subtract, square, average recipe as reconstruction loss.

Task: write snap_to_codebook(codes, codebook).

  • codes is a list of nnn encoder outputs, each a list of ddd numbers.
  • codebook is a list of KKK entries, each a list of ddd numbers.

Return a tuple (indices, counts, error):

  • indices: for each code in order, the position (counting from 0) of its nearest entry. If two entries are exactly as near, take the one that comes first in the codebook.
  • counts: a list of length KKK, where counts[k] is how many codes chose entry k (0 for an entry no code chose).
  • error: the mean of (zj−ej)2(z_j - e_j)^2(zj​−ej​)2 over all n×dn \times dn×d numbers, rounded to 4 decimal places.

Examples

codes = [[0.9, 0.15], [0.2, 0.8], [1.1, -0.2], [0.0, 1.3]]
codebook = [[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0]]
returns ([0, 1, 0, 1], [2, 2, 0], 0.0316)
codes = [[0.6, 0.4], [2.5, 2.0], [0.3, 0.9]]
codebook = [[0.5, 0.5], [3.0, 3.0], [0.0, 1.0]]
returns ([0, 1, 2], [1, 1, 1], 0.2283)

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