Functions and operators

sg⁡[z]\operatorname{sg}[\mathbf{z}] Stop-gradient

The value passes through unchanged, but no gradient flows back through it.

In ML papers

sg⁡[z]\operatorname{sg}[\mathbf{z}] is the identity on the forward pass with zero gradient on the backward pass: the value is used, but training treats it as a constant. In code it is .detach() in PyTorch or jax.lax.stop_gradient in JAX.

It controls which part of a model a loss term trains. The VQ-VAE (Oord et al. 2017) uses ∥sg⁡[ze]−e∥2\|\operatorname{sg}[\mathbf{z}_e] - \mathbf{e}\|^2 to move the codebook toward the encoder output and β∥ze−sg⁡[e]∥2\beta \|\mathbf{z}_e - \operatorname{sg}[\mathbf{e}]\|^2 to move the encoder toward the codebook. SimSiam and BYOL-style methods stop gradients through one branch; target networks in RL do the same for the bootstrapped target. The straight-through estimator is written z+sg⁡[q−z]\mathbf{z} + \operatorname{sg}[\mathbf{q} - \mathbf{z}]: forward it gives q\mathbf{q}, backward it acts like z\mathbf{z}.

How to type it

LaTeXShows
\operatorname{sg}[\mathbf{z}]sg⁡[z]\operatorname{sg}[\mathbf{z}]
\operatorname{stopgrad}(\mathbf{z})stopgrad⁡(z)\operatorname{stopgrad}(\mathbf{z})

A worked example

∂∂w(w⋅sg⁡[w])=sg⁡[w]=w\frac{\partial}{\partial w} \big(w \cdot \operatorname{sg}[w]\big) = \operatorname{sg}[w] = w

Without the stop-gradient, ∂∂ww2=2w\frac{\partial}{\partial w} w^2 = 2w; with it, only one factor counts.

Related

∇θL\nabla_\theta \mathcal{L}Nabla (gradient)∂L∂w\frac{\partial \mathcal{L}}{\partial w}Partial derivativeJ(θ)=Eτ∼πθ[R(τ)]J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[R(\tau)\right]Objective J

Decode this example →