AI Wiki中文/EN

VQ-VAE: learning a vocabulary of latent codes

向量量化自编码器

Quantize an encoder, trace three gradient routes and distinguish code usage from generation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

What if a latent code had to be a word in a vocabulary?

Consider a teaching compressor with only three allowed scalar codes: −1, 0 and 1. Its encoder proposes 0.82. The decoder receives 1, the nearest allowed code, rather than 0.82. This small change creates a useful discrete interface and a difficult training question: how does the encoder improve when small changes to 0.82 leave the transmitted code unchanged?

A vector-quantized variational autoencoder, or VQ-VAE, learns the encoder, a codebook and the decoder. The original paper represents inputs through discrete code indices; the fixed Sonnet implementation makes the gradient routing explicit. Here, “vocabulary” is an analogy for a learned set of vectors, not a claim that the codes must be words. Read VAEs and gradient checking first.

Computed code assignments, hard and surrogate gradients, reconstruction and code priors in a seven-parameter VQ model.
Computed code assignments, hard and surrogate gradients, reconstruction and code priors in a seven-parameter VQ model.

Three objects and two stages

Let the encoder output a D-dimensional vector, and let a codebook contain K vectors of the same dimension. At one latent position, assign the nearest vector using squared Euclidean distance. Ties need a convention; the program chooses the first index.

ze(x)∈RD,E={e1,…,eK},k(x)=arg⁡min⁡j∥ze(x)−ej∥22,zq(x)=ek(x).z_e(x)\in\mathbb R^D,\quad E=\{e_1,\ldots,e_K\},\quad k(x)=\arg\min_j\|z_e(x)-e_j\|_2^2,\quad z_q(x)=e_{k(x)}.

The decoder models an observation given that vector. The encoder’s categorical distribution puts all its mass on the selected index. A uniform prior at this position gives a constant KL term, so it contributes no encoder gradient during this stage.

q(k∣x)=1[k=k(x)],p(k)=1/K,DKL(q∥p)=log⁡K.q(k\mid x)=\mathbf1[k=k(x)],\qquad p(k)=1/K,\qquad D_{\rm KL}(q\Vert p)=\log K.

Section 3.3 of VQ-VAE then learns a prior over the codes after training the autoencoder, using an autoregressive model for structured codes. Generation draws indices from this learned prior and decodes their embeddings. Reconstruction selects indices using an observed input. These are different procedures: a good reconstruction does not establish that drawing arbitrary codebook entries reproduces the data distribution.

Follow the gradient arrows

Write the objective as a quantity to minimize. The reconstruction term is a negative log-likelihood, or an explicitly chosen positive reconstruction error. The paper’s printed Equation 3 uses a positive log-likelihood alongside positive penalties; we use a consistent minimization convention, cross-checked against Sonnet’s positive reconstruction error plus quantizer loss. The stop-gradient operator, sg, leaves the forward value unchanged but contributes zero derivative.

J=Jrec(x,zq)+∥sg⁡[ze]−ek∥22+β∥ze−sg⁡[ek]∥22.J=J_{\rm rec}(x,z_q)+\|\operatorname{sg}[z_e]-e_k\|_2^2+\beta\|z_e-\operatorname{sg}[e_k]\|_2^2.

The codebook term moves selected embeddings toward encoder outputs. The commitment term discourages the encoder from drifting away from its chosen embedding. The decoder gets the reconstruction gradient. For the encoder’s reconstruction path, straight-through estimation replaces the hard assignment’s derivative with an identity route:

zst=ze+sg⁡[zq−ze],zst=zq in the forward pass,∂zst∂ze=I by the backward rule.z_{\rm st}=z_e+\operatorname{sg}[z_q-z_e],\qquad z_{\rm st}=z_q\text{ in the forward pass},\quad \frac{\partial z_{\rm st}}{\partial z_e}=I\text{ by the backward rule}.

This is a surrogate gradient. Away from code boundaries, the actual hard assignment is locally constant, so its derivative with respect to the encoder output is zero. At boundaries it can be discontinuous. A straight-through gradient is neither that derivative nor an ordinary differentiable reparameterization of a discrete sample.

The scalar program has seven parameters. For N observations, the residual is r and the reconstruction loss is half the mean squared error:

ze=ax+b,x^=cek+d,r=x^−x,Jrec=12N∑nrn2.z_e=ax+b,\quad \hat x=c e_k+d,\quad r=\hat x-x,\quad J_{\rm rec}=\frac1{2N}\sum_n r_n^2.

With the stated routing, the encoder receives reconstruction and commitment terms. Codebook updates use only the codebook term; repeated assignments must be accumulated, not overwritten.

un=crn+2β(ze,n−ekn),∂aJ=1N∑nunxn,∂bJ=1N∑nun,∂ejJ=2N∑n:kn=j(ej−ze,n).u_n=c r_n+2\beta(z_{e,n}-e_{k_n}),\quad \partial_a J=\frac1N\sum_n u_nx_n,\quad \partial_bJ=\frac1N\sum_nu_n,\quad \partial_{e_j}J=\frac2N\sum_{n:k_n=j}(e_j-z_{e,n}).

The remaining gradients are mean(r zq) for c and mean(r) for d. To check them with finite differences, freeze the assignments and stop-gradient operands at an anchor parameter vector. Recompute the differentiable operands at each perturbation. The resulting local surrogate has the same value at the anchor and the specified seven gradients. The tests also differentiate the actual hard reconstruction and verify the different, zero encoder derivative. Naming the function being differentiated prevents a misleading “gradient check passed” claim.

A complete scalar model

Save as vqvae.py; run with Python 3.12 and NumPy 1.26.4. The six observations are synthetic teaching data. Initialization, 400 full-batch steps and learning rate 0.02 are fixed; there is no random training step. This implementation uses gradient-updated embeddings, not EMA. For N vectors of dimension D and K codes, a direct assignment costs O(NKD); this vectorized distance matrix stores O(NK) values. The encoder and decoder add their own costs in a larger network.

"""Original scalar VQ-VAE: explicit straight-through surrogate, not a hard derivative."""
import json
import numpy as np

DATA = np.array([-1.3, -1.1, -.9, .7, .9, 1.1])
INITIAL = np.array([.8, .1, 1., 0., -1., 0., 1.])  # a,b,c,d,e0,e1,e2


def inputs(params, x, beta):
    p, x = np.asarray(params, float), np.asarray(x, float)
    if (p.shape != (7,) or x.ndim != 1 or not 1 <= x.size <= 128
            or not np.isfinite(p).all() or not np.isfinite(x).all()
            or np.max(abs(p)) > 10 or np.max(abs(x)) > 4
            or not np.isscalar(beta) or not np.isfinite(beta) or not 0 <= beta <= 10):
        raise ValueError('Seven bounded parameters, 1..128 inputs in [-4,4], beta in [0,10].')
    return p, x


def forward(params, x=DATA, beta=.25):
    p, x = inputs(params, x, beta)
    a, b, c, d = p[:4]
    ze = a*x+b
    k = np.argmin((ze[:, None]-p[4:])**2, axis=1)  # first index wins ties
    zq = p[4:][k]
    error = c*zq+d-x
    reconstruction = float(.5*np.mean(error**2))
    codebook = float(np.mean((ze-zq)**2))
    commitment = beta*codebook
    return dict(ze=ze, codes=k, quantized=zq, reconstruction=reconstruction,
                codebook=codebook, commitment=commitment,
                loss=float(reconstruction+codebook+commitment))


def objective(params, x=DATA, beta=.25):
    p, x = inputs(params, x, beta)
    out = forward(p, x, beta)
    ze, zq, k = out['ze'], out['quantized'], out['codes']
    error = p[2]*zq+p[3]-x
    dze = p[2]*error+2*beta*(ze-zq)
    gradient = np.zeros(7)
    gradient[:4] = [np.mean(dze*x), np.mean(dze), np.mean(error*zq), np.mean(error)]
    np.add.at(gradient[4:], k, 2*(zq-ze)/x.size)
    return out['loss'], gradient


def surrogate(params, anchor, x=DATA, beta=.25):
    """Freeze stop-gradient operands AND assignments at anchor for finite differences."""
    p, x = inputs(params, x, beta)
    fixed = forward(anchor, x, beta)
    ze = p[0]*x+p[1]
    z_st = ze+fixed['quantized']-fixed['ze']
    reconstruction = .5*np.mean((p[2]*z_st+p[3]-x)**2)
    codebook = np.mean((fixed['ze']-p[4:][fixed['codes']])**2)
    commitment = beta*np.mean((ze-fixed['quantized'])**2)
    return float(reconstruction+codebook+commitment)


def code_prior(codes):
    k = np.asarray(codes)
    if (k.ndim != 1 or not 1 <= k.size <= 128 or k.dtype.kind not in 'iu'
            or np.any(k < 0) or np.any(k > 2)):
        raise ValueError('1..128 integer code indices in [0,2] required.')
    p = np.bincount(k, minlength=3)/k.size
    positive = p[p > 0]
    return p, float(np.exp(-np.sum(positive*np.log(positive))))


def train(steps=400, rate=.02):
    if (isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 2000
            or not np.isfinite(rate) or not 0 < rate <= .1):
        raise ValueError('Integer steps in [0,2000] and rate in (0,.1] required.')
    p = INITIAL.copy()
    history = []
    for step in range(steps+1):
        loss, gradient = objective(p)
        history.append([step, loss, forward(p)['reconstruction']])
        if step < steps:
            p -= rate*gradient
    return p, history


def demo():
    p, history = train()
    out = forward(p)
    prior, perplexity = code_prior(out['codes'])
    return dict(initial_loss=history[0][1], final_loss=history[-1][1],
                initial_reconstruction=history[0][2], final_reconstruction=history[-1][2],
                parameters=p.tolist(), codes=out['codes'].tolist(), prior=prior.tolist(),
                perplexity=perplexity, uniform_prior_kl=float(np.log(3)),
                decoded_codebook=(p[2]*p[4:]+p[3]).tolist(),
                checkpoints=history[::100])


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

A code can exist without being useful

The reconstruction loss falls from about 0.018333 to 0.013352. Assignments are [0,0,0,2,2,2]; the middle code receives no update. Decoded entries are approximately −1.106195, −0.060017 and 0.906013. A uniform prior would allocate one third of its mass to the unused middle code, whereas the fitted categorical prior assigns it zero mass.

Code usage can be summarized by the exponential of the empirical assignment entropy:

p^j=#{n:kn=j}N,perplexity⁡=exp⁡ ⁣(−∑j:p^j>0p^jlog⁡p^j).\hat p_j=\frac{\#\{n:k_n=j\}}N,\qquad \operatorname{perplexity}=\exp\!\left(-\sum_{j:\hat p_j>0}\hat p_j\log\hat p_j\right).

Here the prior is [0.5,0,0.5] and perplexity is 2, although K=3. This statistic measures assignment diversity in the measured sample. It is not a likelihood score, a reconstruction guarantee or proof that every code has a useful meaning. Unused codes and a decoder ignoring its latent input are distinct failure mechanisms. The paper discusses posterior collapse as motivation, but its design should not be paraphrased as a universal guarantee against all representation failures.

The scalar categorical prior has no spatial dependence. Image models require many latent positions, expressive networks and an appropriate learned prior. The Sonnet source also offers a different EMA quantizer; the paper states that EMA was not used in its reported experiments. A later implementation’s default is not evidence about an earlier experiment.

Predict before running

  1. With codes −1,0,1, which code receives encoder output 0.82? What happens to the transmitted value if it becomes 0.83?

Answer: Both select 1. The hard forward map is locally constant; a nonzero straight-through gradient therefore follows a surrogate rule.

  1. Half the observations select code 0 and half code 2. Calculate perplexity and the one-position KL to a uniform three-code prior for a deterministic encoder.

Answer: Assignment entropy is log2, so perplexity is 2. For each deterministic encoder output, KL is log3≈1.098612. The empirical distribution across inputs and the conditional distribution for one input are different objects.

  1. Set β to zero. Does that stop the encoder from learning? Does it send reconstruction gradients into codebook entries?

Answer: It removes commitment gradients. The encoder still receives the straight-through reconstruction signal; embeddings still receive their separate codebook gradient, not the reconstruction gradient under this implementation’s routing.

  1. An image model reconstructs well. Is a uniform random code grid a justified generation procedure?

Answer: Not from reconstruction alone. Measure code usage and dependencies, fit and evaluate a prior, then sample from it. Independent uniform codes can combine individually available entries into configurations not learned from data.

Reading the papers as separate claims

Read the VQ-VAE paper in order: nearest-code representation in Section 3.1, gradient routes in 3.2, then the learned prior in 3.3. First submitted in 2017, the inspected v2 is dated 2018-05-30. Compare its three loss roles with the fixed Sonnet quantizer, then trace the positive reconstruction error in the same repository’s example notebook. The code explains an implementation choice; the paper explains the model and the scope of its original experiments. Neither source makes our seven-parameter example an image-model reproduction.

Make a prediction, then check

Does the straight-through gradient equal the true hard-quantizer derivative?

Choose one answer

Learning objectives

  • Explain nearest-code quantization.
  • Derive the specified gradient routes.
  • Check a straight-through surrogate honestly.
  • Separate codebook learning and prior learning.

Prerequisites & connections

Explore related knowledge →

References

  1. Neural Discrete Representation Learning (v2): discrete codes and training
    Aäron van den Oord; Oriol Vinyals; Koray Kavukcuoglu · 2018
  2. Sonnet VectorQuantizer at 4a3bae0
    Google DeepMind and Sonnet contributors · 2026

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked VQ-VAE v2 selected method sections and fixed Sonnet quantizer/example loss. Seven paired equations, four explained exercises and a seven-parameter original scalar model. All surrogate gradients checked, with a separate true-hard-derivative counterexample; no image benchmark or EMA reproduction.

  • Checked all7 gradients against the anchored ST surrogate, hard encoder derivative zero away from boundaries, codebook scatter, commitment routing,400 updates, code entropy and prior mismatch. Positive minimization convention clarified against printed Equation3 and implementation.
  • Four computed SVGs bind each actual bilingual program. Group passed16 numerical/geometry checks and24 isolated responsive cases at390/768/1536 with four fallback fonts. Eight final representative screenshots actually viewed. Added VQ numeric labels and equal-unit phase axes with preserved originals; data unchanged. Full article-page acceptance is separate, not independent human review.

Source locations checked:

  • Neural Discrete Representation Learning (v2): discrete codes and training · Read selected Sections3.1–3.3; inspected PDF page4. First2017-11-02; v2 dated2018-05-30. Checked ST, codebook/commitment, uniform prior and separate learned prior. Equation3 sign convention clarified with positive reconstruction implementation. No full appendix or experiment replication.
  • Sonnet VectorQuantizer at 4a3bae0 · Read lines95–130 and VQVAEModel in cell9 of examples/vqvae_example.ipynb at the same commit. Commit2026-07-07. Apache2.0 header identified, not a full license audit; reference only, no copied code or upstream execution.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.