Search

Search papers and lessons

Gumbel-Softmax Trick

Level 3 · 13 min read

The Gumbel-softmax trick replaces a hard random choice among categories with a smooth softmax over noisy scores, so gradients can flow through a discrete sample.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Linear algebra
  • Sampling
  • Generative models
  • ReadReady to readNot yet

TL;DR

Many models must pick one category from a list, such as a discrete code, a word or an architectural choice, and training needs gradients to flow through that pick. A hard pick cannot be differentiated, because a tiny change in the scores either changes nothing or flips the choice. The Gumbel-softmax trick adds independent Gumbel noise to the scores, then applies a Softmax with a temperature, which gives a smooth vector that behaves like a one-hot sample when the temperature is small.

Builds on: Categorical Distribution, Gumbel Distribution, Softmax, Reparameterization Trick · Leads to: discrete latent-variable models and relaxed sampling in general

Where it's used

Discrete codes in autoencoders. A variational autoencoder whose latent code is a choice among categories needs to sample that choice and still train by gradient descent. The Gumbel-softmax relaxation gives a differentiable sample, so the encoder can be trained end to end. Jang, Gu and Poole introduced the trick in 2016, and their experiments include this setting.

Image tokenizers. The first stage of DALL-E, which turns an image into a grid of discrete tokens, used a discrete autoencoder trained with a Gumbel-softmax relaxation over a codebook of tokens, so that the choice of each token could be learned by gradients.

Choosing among architecture operations. In neural architecture search, a network can choose one operation (a convolution, a pooling layer, or a skip connection) at each position. Each choice is a categorical variable. The relaxation lets the search learn the choice weights with gradients instead of trying every option.

Routing and gating. A model that sends each input to one of several experts, or that picks one action from a discrete set, can use the same relaxation during training. At test time the hard choice is often used, which is why the gap between training and test behaviour is a practical concern.

How it works

Take one tiny instance with three categories and the probabilities from the categorical lesson: p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2). The scores we will work with are log⁡pk\log p_k, the logarithms of the probabilities, which are (−0.69,−1.20,−1.61)(-0.69, -1.20, -1.61) to two decimals.

  1. Start from the scores. Each category has a score log⁡pk\log p_k. Higher score means more likely. The scores are −0.69-0.69, −1.20-1.20 and −1.61-1.61. Check: the largest score belongs to the most likely category, which is category 1 with probability 0.5.
  2. Add Gumbel noise. Draw one independent Gumbel value per category. Say the draws are g=(0.50,−0.20,1.00)g = (0.50, -0.20, 1.00). Add them to the scores: sk=log⁡pk+gks_k = \log p_k + g_k, which gives s=(−0.19,−1.40,−0.61)s = (-0.19, -1.40, -0.61). Check: each noisy score is the old score plus its own noise, so the noise for one category does not touch another.
  3. Take the hard choice. The largest noisy score is −0.19-0.19, in category 1. A hard sample picks category 1, which is the output of the Gumbel-max trick and is an exact sample from the categorical distribution. Check: the hard choice is not differentiable, because a tiny change in any score leaves the choice unchanged until the top two scores swap.
  4. Soften the choice. Replace "take the largest" with a Softmax over the noisy scores at temperature τ=1\tau = 1. Exponentiate each score (the exponential): e−0.19=0.827e^{-0.19} = 0.827, e−1.40=0.247e^{-1.40} = 0.247, e−0.61=0.543e^{-0.61} = 0.543. Divide each by the total 1.6171.617 to get y=(0.511,0.153,0.336)y = (0.511, 0.153, 0.336). Check: the entries are positive and add up to 1, so yy is a probability vector, but it is spread out rather than one-hot.
  5. Sharpen with a small temperature. Divide each score by τ=0.1\tau = 0.1 before the softmax. The scores become (−1.9,−14.0,−6.1)(-1.9, -14.0, -6.1), and the softmax gives about y=(0.985,0.000,0.015)y = (0.985, 0.000, 0.015). Check: the largest entry is near 1 and the others are near 0, so yy looks like the hard choice of step 3.

The flow below shows the same steps. The noise makes the choice random, the softmax makes it smooth, and the temperature sets how close to a hard choice the output is.

flowchart LR
  A["Scores log p_k"] --> B["Add Gumbel noise g_k"]
  B --> C["Divide by temperature tau"]
  C --> D["Softmax"]
  D --> E["Soft sample y, near one-hot when tau is small"]

The math

Definition

Definition: Gumbel-softmax sample

Let log⁡pk\log p_k be the scores of KK categories, let g1,…,gKg_1, \ldots, g_K be independent standard Gumbel draws, and let τ>0\tau \gt 0 be a temperature. The Gumbel-softmax sample is the vector y\mathbf{y} with entries

yk=exp⁡((log⁡pk+gk)/τ)∑j=1Kexp⁡((log⁡pj+gj)/τ),k=1,…,K.y_k = \frac{\exp\bigl((\log p_k + g_k)/\tau\bigr)}{\sum_{j=1}^{K} \exp\bigl((\log p_j + g_j)/\tau\bigr)}, \qquad k = 1, \ldots, K.

Each yky_k lies between 0 and 1, and the yky_k sum to 1, so y\mathbf{y} lies on the probability simplex.

The symbols log⁡pk\log p_k are the scores, the gkg_k are the noise, and τ\tau is the temperature. In practice the scores are the outputs of the model before the softmax, which are called logits, and log⁡pk\log p_k is replaced by the logit αk\alpha_k.

Step 1 in symbols: the scores

For the walkthrough, p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2) gives

log⁡p=(log⁡0.5,log⁡0.3,log⁡0.2)≈(−0.69,−1.20,−1.61).\log p = (\log 0.5, \log 0.3, \log 0.2) \approx (-0.69, -1.20, -1.61).

The logarithm is used because the Gumbel-max argument is stated for log⁡pk\log p_k, and it turns products of probabilities into sums.

Step 2 in symbols: the noise

Each gkg_k is drawn independently from a standard Gumbel distribution. The draws do not depend on the parameters of the model, which matters for the gradient in step 4. In the walkthrough, g=(0.50,−0.20,1.00)g = (0.50, -0.20, 1.00), so sk=log⁡pk+gks_k = \log p_k + g_k gives s=(−0.19,−1.40,−0.61)s = (-0.19, -1.40, -0.61).

Step 3 in symbols: the hard choice and its soft version

The hard choice is

z=arg⁡max⁡ksk,z = \arg\max_k s_k,

which for the walkthrough is z=1z = 1. The soft version replaces the arg⁡max⁡\arg\max with a softmax over the same scores:

yk=esk/τ∑jesj/τ.y_k = \frac{e^{s_k/\tau}}{\sum_j e^{s_j/\tau}}.

At τ=1\tau = 1 the entries are (0.511,0.153,0.336)(0.511, 0.153, 0.336), as in step 4 of the walkthrough.

Step 4 in symbols: the gradient

The noise gkg_k is fixed once it is drawn, so the sample is a deterministic function of the parameters αk\alpha_k and the noise. Writing y=softmax((α+g)/τ)\mathbf{y} = \mathrm{softmax}((\boldsymbol{\alpha} + \mathbf{g})/\tau) makes the reparameterization explicit: the randomness is in g\mathbf{g}, and y\mathbf{y} is a smooth function of α\boldsymbol{\alpha}. The derivative with respect to αk\alpha_k exists, so gradient descent can train it, which the reparameterization trick requires.

Step 5 in symbols: the temperature limits

As τ→0\tau \to 0, the largest entry of y\mathbf{y} approaches 1 and the rest approach 0, so y\mathbf{y} approaches the one-hot vector of the hard choice. As τ→∞\tau \to \infty, every entry approaches 1/K1/K. For the walkthrough, τ=0.1\tau = 0.1 gives y≈(0.985,0.000,0.015)y \approx (0.985, 0.000, 0.015), which is near one-hot, and τ=1\tau = 1 gives a spread-out vector.

Worked examples

Example
1. Two categories, no noise

Two categories have scores s=(1,0)s = (1, 0), and we use τ=1\tau = 1.

  1. Exponentiate the scores: e1=2.718e^1 = 2.718 and e0=1e^0 = 1.
  2. The total is 2.718+1=3.7182.718 + 1 = 3.718.
  3. The soft sample is y=(2.718/3.718,1/3.718)=(0.731,0.269)y = (2.718/3.718, 1/3.718) = (0.731, 0.269).
  4. Check: 0.731+0.269=1.0000.731 + 0.269 = 1.000, so yy is a valid probability vector.
  5. Now lower the temperature to τ=0.5\tau = 0.5. The scores become (2,0)(2, 0). Exponentiate: e2=7.389e^2 = 7.389, so y=(7.389/8.389,1/8.389)=(0.881,0.119)y = (7.389/8.389, 1/8.389) = (0.881, 0.119).
  6. Check: the entries still sum to 1, and the top entry rose from 0.731 to 0.881.
  7. Interpretation: a smaller temperature makes the output closer to a hard choice of the top category.
Example
2. The standard case from the walkthrough

Take p=(0.2,0.8)p = (0.2, 0.8) and noise g=(1.0,0.0)g = (1.0, 0.0), with τ=1\tau = 1.

  1. The scores are log⁡p=(log⁡0.2,log⁡0.8)=(−1.61,−0.22)\log p = (\log 0.2, \log 0.8) = (-1.61, -0.22) to two decimals.
  2. Add the noise: s=(−1.61+1.00,−0.22+0.00)=(−0.61,−0.22)s = (-1.61 + 1.00, -0.22 + 0.00) = (-0.61, -0.22).
  3. The hard choice is the largest score, −0.22-0.22, which is category 2.
  4. Exponentiate: e−0.61=0.544e^{-0.61} = 0.544 and e−0.22=0.800e^{-0.22} = 0.800.
  5. The total is 0.544+0.800=1.3440.544 + 0.800 = 1.344.
  6. The soft sample is y=(0.544/1.344,0.800/1.344)=(0.405,0.595)y = (0.544/1.344, 0.800/1.344) = (0.405, 0.595).
  7. Check: the entries sum to 1.0001.000, and the largest entry is in category 2, matching the hard choice.
  8. Interpretation: the noise shifted category 1 up by 1.0, but the soft sample still gives category 2 more weight, because the original probability of category 2 is so much larger.
Example
3. A discrete code in a model

An encoder gives a categorical latent code with three values and probabilities p=(0.6,0.3,0.1)p = (0.6, 0.3, 0.1). The noise draws are g=(0.3,0.1,−0.5)g = (0.3, 0.1, -0.5).

  1. The scores are log⁡p=(−0.51,−1.20,−2.30)\log p = (-0.51, -1.20, -2.30) to two decimals.
  2. Add the noise: s=(−0.21,−1.10,−2.80)s = (-0.21, -1.10, -2.80).
  3. The hard choice is the largest score, −0.21-0.21, which is code 1.
  4. Use τ=0.5\tau = 0.5 and divide each score by 0.5: (−0.42,−2.21,−5.61)(-0.42, -2.21, -5.61).
  5. Subtract the largest value, −0.42-0.42, from each entry to keep the numbers small: (0,−1.79,−5.19)(0, -1.79, -5.19). Subtracting the same constant from every entry does not change the softmax.
  6. Exponentiate: e0=1e^0 = 1, e−1.79=0.167e^{-1.79} = 0.167 and e−5.19=0.0056e^{-5.19} = 0.0056.
  7. The total is 1+0.167+0.0056=1.1731 + 0.167 + 0.0056 = 1.173.
  8. The soft sample is y=(0.852,0.142,0.005)y = (0.852, 0.142, 0.005), with the entries summing to 1 up to rounding.
  9. Interpretation: the encoder's gradient flows through these three numbers, and the decoder sees a nearly one-hot code that still changes smoothly when the encoder's parameters change.

Try it: using the same scores and noise from example 3, what does yy become at τ=0.1\tau = 0.1? Answer: dividing by 0.1 gives (−2.1,−11.0,−28.0)(-2.1, -11.0, -28.0), and subtracting the largest entry gives (0,−8.9,−25.9)(0, -8.9, -25.9). The exponentials are about 11, 0.00010.0001 and 00, so y≈(1.000,0.000,0.000)y \approx (1.000, 0.000, 0.000), which is essentially the hard choice of code 1.

Common mistakes and tradeoffs

Mistake 1: "The Gumbel-softmax sample is an exact sample from the categorical distribution." It is tempting to think that adding Gumbel noise gives the right answer at every temperature. In fact only the hard arg⁡max⁡\arg\max of the noisy scores is exact (the Gumbel-max trick). The softmax version is a smooth approximation whose bias shrinks as the temperature falls. At finite τ\tau the sample is biased, and the size of the bias is the price of a gradient.

Mistake 2: "A higher temperature makes the sample sharper." It is tempting to read τ\tau as a sharpness knob that works like a multiplier on the probabilities. In fact dividing by a small τ\tau magnifies the differences between scores, so the softmax concentrates on the top entry. A large τ\tau shrinks the differences, so the output goes toward uniform.

Mistake 3: "The noise is learned." It is tempting to think the Gumbel draws are part of the model. In fact they are fresh random numbers at each step, not parameters. The model learns only the logits αk\alpha_k, and the noise is what makes the sample random while keeping the expression differentiable in αk\alpha_k.

Tradeoffs. A low temperature gives samples close to one-hot and so a model close to the discrete one, but the gradients become large and noisy. A high temperature gives smooth gradients but outputs that do not look like real discrete choices. Many systems anneal the temperature from a high value to a lower one during training. A common variant, the straight-through estimator, uses the hard choice in the forward pass and the soft gradient in the backward pass. The forward pass is then exactly discrete, but the gradient is biased in a different way.

When to use it. Use it when you need to backpropagate through a choice among a small, fixed set of categories and an exact discrete sample is not essential during training.

When not to use it. If the sample only needs to be drawn once, for example at inference, a plain categorical sample is enough. If the categories are continuous, use the reparameterization trick directly. For a large number of categories, a learned embedding or a score-function estimator such as REINFORCE may be more practical.

History

Emil Julius Gumbel studied the largest and smallest values in samples, and his 1958 book Statistics of Extremes made the distribution that bears his name a standard tool in extreme value theory. The Gumbel-max fact, that adding Gumbel noise to log-probabilities and taking the largest gives an exact categorical sample, was used in statistics and later in machine learning for sampling. The version used in deep learning came in 2016. Two groups, Jang, Gu and Poole, and Maddison, Mnih and Teh, posted their papers in November 2016, each introducing a softmax relaxation of a categorical sample with a temperature. The trick caught on because it let discrete latent variables be trained with the same gradient methods as everything else in a neural network.

Recap

  • A hard choice among categories cannot be differentiated, so training needs a smooth stand-in.
  • Adding independent Gumbel noise to the log-probabilities and taking the largest gives an exact categorical sample.
  • Replacing the largest with a softmax over the same noisy scores gives a differentiable sample y\mathbf{y}.
  • The temperature τ\tau controls how close y\mathbf{y} is to one-hot: small τ\tau is sharp and biased, large τ\tau is smooth and spread out.
  • The noise is fixed and independent of the parameters, so the gradient with respect to the logits exists.

Read next: Softmax Temperature, which explains the temperature on its own, and the papers by Jang, Gu and Poole and by Maddison, Mnih and Teh, which introduced the trick in 2016.

Check yourself

QuestionWhy does a hard categorical choice block gradient-based training, and what does the Gumbel-softmax sample replace it with?Show answer

A hard choice is the output of an arg⁡max⁡\arg\max, which is piecewise constant: a small change in the scores leaves it unchanged, and at the point where the top two scores swap it jumps. Its derivative is zero almost everywhere, so there is no gradient to follow. The Gumbel-softmax sample replaces it with a softmax over the noisy scores, which is smooth in the scores and so has a derivative.

QuestionTwo categories have scores s=(0,2)s = (0, 2) and temperature τ=1\tau = 1. What is the soft sample yy, and which category does the hard choice pick?Show answer

The exponentials are e0=1e^0 = 1 and e2=7.389e^2 = 7.389. The total is 8.3898.389. So y=(1/8.389,7.389/8.389)=(0.119,0.881)y = (1/8.389, 7.389/8.389) = (0.119, 0.881). The hard choice is the largest score, which is 2, so category 2 is picked. The soft sample puts most of its weight on category 2, as it should.

QuestionA colleague says that because the temperature is 0.01, the Gumbel-softmax sample is exactly the categorical sample. Explain what is right and what is wrong about this claim.Show answer

What is right is that a small temperature makes the sample close to one-hot, so it approximates the hard choice. What is wrong is the word exactly: at any finite temperature the softmax is a smooth approximation, and the sample is biased relative to the true categorical sample. Only the hard arg⁡max⁡\arg\max of the noisy scores is exact, and the approximation improves only as the temperature goes toward zero.

QuestionIn example 1, the scores are (1,0)(1, 0). What happens to the soft sample if the temperature rises to τ=100\tau = 100?Show answer

Dividing the scores by 100 gives (0.01,0)(0.01, 0). The exponentials are e0.01=1.010e^{0.01} = 1.010 and 11, with total 2.0102.010. So y=(1.010/2.010,1/2.010)=(0.502,0.498)y = (1.010/2.010, 1/2.010) = (0.502, 0.498). The output is close to uniform, which is what a very large temperature does.

Sources