Search

Search papers and lessons

Straight-Through Estimator

Level 4 · 12 min read

The straight-through estimator trains through a hard, non-differentiable step by using the forward value and pretending the step was the identity when gradients flow backwards.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Efficiency
  • Generative models
  • Sign in to see your progress

TL;DR

Many useful network operations are hard decisions: a threshold, a rounding step, a sampled category. Their true derivative is zero almost everywhere, so backpropagation learns nothing through them. The straight-through estimator keeps the hard operation in the forward pass, then in the backward pass treats it as if it were the identity, so the gradient reaches the inputs anyway.

Where you'll see it: training binarized and low-precision networks, the discrete codebook lookup in VQ-VAE, and sampling categorical latent variables in world models.

Intuition

A gate with a broken speedometer

Think of a light switch that reads the room brightness and turns on above some level. To tune the threshold you need to know whether nudging the brightness reading would change the output. For a switch, it almost never does: nudge the reading by a little and the light is still on or still off. The only moment anything changes is at the exact threshold, where the output jumps. Calculus sees a flat floor with a cliff at one point, and the flat part tells the learner nothing.

The straight-through estimator takes a shortcut. It runs the real switch on the forward pass, so the network does the real thing. On the backward pass it says: "pretend the switch was a wire." The error signal coming back from the output is handed straight through to the input, scaled by one. The learner gets a usable direction even though the true slope is useless.

The name comes from that picture. The gradient goes straight through the non-differentiable block as if it were not there.

Why we need it

Backpropagation is the Chain Rule applied backwards through a computation graph (see Backpropagation). Every link in the chain has to have a derivative. Three common operations break this:

  • a hard threshold, which outputs 1 above zero and 0 below;
  • rounding a real number to the nearest integer or to a low-precision grid;
  • drawing a sample from a categorical distribution, because the sample is an integer.

Each of these is piecewise constant. Wherever the derivative exists it is zero, and at the jumps it does not exist at all. Without a workaround, the gradient reaching anything upstream of the operation is zero, and training stops. The straight-through estimator is the workaround most often used because it is a one-line change in the backward pass and it works surprisingly well.

The math

Definition: Hard threshold

For a real input xx, the hard threshold H(x)H(x) returns 11 if x>0x \gt 0 and 00 otherwise. Its output is h=H(x)h = H(x), and the loss LL depends on xx only through hh.

The chain rule and where it breaks

Write the loss as a composition L(H(x))L(H(x)). The chain rule gives

∂L∂x=∂L∂h⋅dHdx.\frac{\partial L}{\partial x} = \frac{\partial L}{\partial h}\cdot \frac{dH}{dx}.

The factor dHdx\frac{dH}{dx} is 00 for every x≠0x \ne 0, because HH is flat there. At x=0x = 0 it is undefined, since HH jumps. So the gradient is 00 almost everywhere, and the product with ∂L∂h\frac{\partial L}{\partial h} is always 00.

The estimator

The straight-through estimator replaces the undefined factor with a surrogate g(x)g(x) and keeps the rest of the chain rule:

∂L∂x≈∂L∂h⋅g(x).\frac{\partial L}{\partial x} \approx \frac{\partial L}{\partial h}\cdot g(x).

The forward pass still computes h=H(x)h = H(x). Only the backward pass changes. Three common choices of gg are:

  • Identity: g(x)=1g(x) = 1. The gradient passes through unchanged. This is the classic form.
  • Clipped identity: g(x)=1[ ∣x∣≤1 ]g(x) = \mathbf{1}[\,|x| \le 1\,], where 1[⋅]\mathbf{1}[\cdot] is 11 when the condition holds and 00 otherwise. Inputs far outside the range stop receiving gradient, which keeps saturated units from drifting. Hubara et al. use this form for binarized activations.
  • Sigmoid derivative: g(x)=σ′(x)g(x) = \sigma'(x), where σ(x)=1/(1+e−x)\sigma(x) = 1/(1+e^{-x}) is the Sigmoid Function. Bengio et al. (2013) tried this as a variant for stochastic binary units, where the forward pass samples a bit from a sigmoid probability, and reported better results without multiplying by the sigmoid derivative than with it.
−2−1.5−1−0.500.511.52−1.5−1−0.500.511.5xvalue
  • forward: sign(x)
  • STE backward: g = 1
  • true derivative (0 away from 0)
The forward pass jumps at x = 0. The true derivative is flat zero, so no signal flows. The straight-through estimator replaces that zero with 1.

Stochastic and categorical units

The same idea applies when the forward pass draws a random sample. Suppose hh is a Bernoulli sample with probability p=σ(x)p = \sigma(x). The sampling step has no useful derivative with respect to pp. The plain estimator copies the gradient with respect to hh onto the pre-sigmoid input xx, ∂h∂x≈1\frac{\partial h}{\partial x} \approx 1. The variant above instead multiplies by the sigmoid slope, ∂h∂x≈σ′(x)\frac{\partial h}{\partial x} \approx \sigma'(x). For a categorical latent, the same rule is applied per category to the softmax probabilities, which is how the sampled categorical latents in some world models are trained.

Worked examples

Example
One threshold unit, one step at a time

Setup: x=0.4x = 0.4, the target is y=0y = 0, the loss is L=(h−y)2=h2L = (h - y)^2 = h^2, the learning rate is η=0.1\eta = 0.1, and the surrogate is g=1g = 1.

  1. Forward: h=H(0.4)=1h = H(0.4) = 1, so L=12=1L = 1^2 = 1.
  2. True gradient: ∂L∂h=2h=2\frac{\partial L}{\partial h} = 2h = 2. Then dHdx=0\frac{dH}{dx} = 0 at x=0.4x = 0.4, so ∂L∂x=2⋅0=0\frac{\partial L}{\partial x} = 2 \cdot 0 = 0. The weight does not move.
  3. STE gradient: ∂L∂x≈2⋅1=2\frac{\partial L}{\partial x} \approx 2 \cdot 1 = 2.
  4. Update: x←0.4−0.1⋅2=0.2x \leftarrow 0.4 - 0.1 \cdot 2 = 0.2.
  5. Repeat. At x=0.2x = 0.2 the output is still h=1h = 1, so L=1L = 1 and the STE gradient is 22 again. Update: x←0.2−0.2=0.0x \leftarrow 0.2 - 0.2 = 0.0.
  6. At x=0.0x = 0.0 the threshold has flipped: H(0)=0H(0) = 0, so h=0h = 0 and L=0L = 0. The gradient ∂L∂h=2(h−y)=0\frac{\partial L}{\partial h} = 2(h - y) = 0, so the STE gradient is 00 and learning stops.

Interpretation: the estimator moved the threshold across the decision boundary in two steps, which is the behaviour we wanted. It also shows the stopping condition: once the loss is zero, the signal is gone.

Example
A binary activation with a clipped surrogate

Setup: the forward activation is h=sign⁡(x)h = \operatorname{sign}(x), which is +1+1 or −1-1. The backward surrogate is the clipped identity g(x)=1[ ∣x∣≤1 ]g(x) = \mathbf{1}[\,|x| \le 1\,]. Two units have pre-activations x1=0.3x_1 = 0.3 and x2=1.7x_2 = 1.7. The upstream gradient is ∂L∂h=0.8\frac{\partial L}{\partial h} = 0.8 for both.

  1. Unit 1: ∣x1∣=0.3≤1|x_1| = 0.3 \le 1, so g(x1)=1g(x_1) = 1. The gradient is ∂L∂x1=0.8⋅1=0.8\frac{\partial L}{\partial x_1} = 0.8 \cdot 1 = 0.8.
  2. Unit 2: ∣x2∣=1.7>1|x_2| = 1.7 \gt 1, so g(x2)=0g(x_2) = 0. The gradient is ∂L∂x2=0.8⋅0=0\frac{\partial L}{\partial x_2} = 0.8 \cdot 0 = 0.
  3. Interpretation: unit 2 is already far past the threshold. A small change in its pre-activation would not change its sign, so the estimator refuses to push it further. Unit 1 sits near the boundary, where the sign can still flip, and it receives the full signal.

This is why the clipped form is preferred for binarized networks: without it, units can drift into a range where their gradients are large but the output never changes.

Example
The same behaviour in a few lines of Python

This script runs the first example. It was executed for this lesson, and the output below is its real output.

def step(x):
    return 1.0 if x > 0 else 0.0
 
def train(x, lr=0.1, target=0.0, steps=4, use_ste=True):
    for t in range(steps):
        h = step(x)
        loss = (h - target) ** 2
        dL_dh = 2 * (h - target)
        dh_dx = 1.0 if use_ste else 0.0
        grad = dL_dh * dh_dx
        print(f"step {t}: x={x:.2f} h={h:.0f} loss={loss:.2f} dL/dh={dL_dh:.2f} dL/dx={grad:.2f}")
        x = x - lr * grad
    return x
 
print("with STE")
train(0.4)
print("true gradient")
train(0.4, use_ste=False)

Output:

with STE
step 0: x=0.40 h=1 loss=1.00 dL/dh=2.00 dL/dx=2.00
step 1: x=0.20 h=1 loss=1.00 dL/dh=2.00 dL/dx=2.00
step 2: x=0.00 h=0 loss=0.00 dL/dh=0.00 dL/dx=0.00
step 3: x=0.00 h=0 loss=0.00 dL/dh=0.00 dL/dx=0.00
true gradient
step 0: x=0.40 h=1 loss=1.00 dL/dh=2.00 dL/dx=0.00
step 1: x=0.40 h=1 loss=1.00 dL/dh=2.00 dL/dx=0.00
step 2: x=0.40 h=1 loss=1.00 dL/dh=2.00 dL/dx=0.00
step 3: x=0.40 h=1 loss=1.00 dL/dh=2.00 dL/dx=0.00

The true-gradient run never moves, while the STE run crosses the threshold in two steps.

Tradeoffs and failure modes

The estimator is a cheap and often effective fix, but it is a heuristic. The table lists the situations where it helps and where it goes wrong.

SituationWhat goes wrongBetter choice
Binary or low-bit weights and activationsSurrogate gradient ignores saturation, so units drift far from the boundaryClipped identity, or a learned scale
Discrete latent codes (for example a codebook lookup)Gradient for the codebook itself is missing, since the lookup is not reached by the STEAdd a separate codebook loss, as in VQ-VAE
Sampling from a categorical with many categoriesHigh variance across samples, slow learningGumbel-softmax relaxation with a temperature, or a score-function estimator
A gradient that must be exact (for example, for a variational bound)The estimate is biased, so the optimizer may converge to the wrong placeReparameterization where the distribution allows it (see Reparameterization Trick), or a score-function estimator (see Score Function)
Rounding during quantization-aware trainingGradient ignores rounding error, so the model can settle where the rounded weights are poorKeep a full-precision copy and round only in the forward pass, or fine-tune after rounding

A practical warning: the STE does not compute a gradient of the loss, so a gradient check against finite differences will fail. The test should compare the STE against the surrogate network it actually implements, not against the true derivative of the hard model.

Another failure mode is the learning-rate interaction. Because the estimator moves inputs whose output does not change, a parameter can drift a long way with no effect on the loss. Gradient clipping and careful initialisation of pre-activations help keep the drift bounded.

History

The idea was proposed by Geoffrey Hinton in a 2012 lecture (lecture 15b of his neural networks course, as cited by Bengio et al.). Yoshua Bengio, Nicholas Léonard and Aaron Courville named it the straight-through estimator in 2013 and compared it with other estimators for stochastic binary neurons. They found it simple to implement and, in their small experiment, it gave the best validation and test error. Their motivation was conditional computation: they wanted networks that switch parts of themselves on and off, and a gate that must make a hard decision needs some gradient to learn from.

Hubara, Courbariaux and colleagues used it in 2016 to train networks whose weights and activations were binary, which makes the forward pass cheap but rules out exact gradients. Their version is the clipped form, which accounts for saturation. Van den Oord, Vinyals and Kavukcuoglu used the estimator in the VQ-VAE paper in 2017, where the nearest-codebook lookup has no derivative, and they copy the decoder's gradient to the encoder output.

Check yourself

QuestionA hard threshold H(x) outputs 1 when x is positive and 0 otherwise. What is its true derivative at x = 2, and why can't backpropagation use it to learn?Show answer

The true derivative is 0. H is constant on each side of zero, so a small change in x leaves the output unchanged, and the chain rule multiplies the upstream gradient by 0. Learning stops because nothing upstream of the threshold receives a usable signal. The straight-through estimator replaces the 0 with a surrogate, usually 1.

QuestionA unit has pre-activation x = 0.5, upstream gradient dL/dh = -0.6, and the clipped surrogate g(x) = 1 if |x| is at most 1, else 0. What gradient reaches x?Show answer

Since |0.5| is at most 1, g(0.5) = 1. The gradient is -0.6 times 1, which is -0.6. The clipped form lets the full signal through here, because the unit is close enough to the threshold for a small change to flip its sign.

QuestionWhy is the straight-through gradient not the gradient of the loss, and why does training still work?Show answer

The forward pass uses the hard step, but the backward pass uses a surrogate, usually the identity. So the estimate is the exact gradient of a different network, one with the step replaced by a wire. It is biased for inputs where the wire and the step disagree. It still works in practice because the direction it gives is usually correct, and the forward pass always reflects the real discrete model, so the loss we measure is the real one.

QuestionA categorical latent is sampled from a softmax with probabilities (0.2, 0.5, 0.3) and the sampled category is the second one. Under a sigmoid-style straight-through rule applied per category, what is the surrogate derivative of the sampled probability p = 0.5 with respect to its logit, using p(1 minus p)?Show answer

The derivative is p(1 - p) = 0.5 times 0.5, which is 0.25. The sampled category contributes its gradient scaled by 0.25. The rule uses the probability of the drawn category as if the draw were a smooth function of that probability, which is the sigmoid-derivative variant described in the math section.

QuestionName one situation where you would prefer the score-function estimator to the straight-through estimator, and say why.Show answer

When an unbiased gradient is needed, for example inside a variational bound where a biased gradient can move the optimizer to the wrong solution. The score-function estimator is unbiased but tends to have high variance, so the choice is between an exact-in-expectation but noisy estimate and a biased but low-variance one. The reparameterization trick is the other option when the distribution allows it.

Sources