advanced29 min studyLesson 494 in Engineering

Shift exponential losses before they overflow

Derive shifted log-sum-exp and direct log-probability losses while preserving finite-input domains and recognizing already lost logits.

On this page

What you’ll understand

  • Derive a maximum-shifted log-sum-exp for a nonempty finite logit vector.
  • Compute cross-entropy directly without materializing a tiny probability and taking its logarithm.
  • State exceptional-input and earlier-quantization limits of the stable reformulation.

Classification losses often combine exponentials, sums, and logarithms. Their exact formulas can be simple while a direct low-precision evaluation overflows or rounds a probability to zero before taking its logarithm. Algebraic reformulation changes the intermediate magnitudes without changing the intended finite-input function. It is a targeted numerical improvement, not a guarantee that arbitrary infinities, masks, or earlier quantization become meaningful. We will derive the formula and inspect its domain.

Factor out the largest exponential

For a nonempty vector of finite logits, choose its largest value m. Factoring exp(m) from the sum gives log-sum-exp as m plus the logarithm of a sum of exp(z_i minus m). Every shifted exponent is at most zero, so its exponential is at most one, and at least one term is one. This avoids overflowing each large positive exponential individually. It can still lose negligible tiny terms to underflow, and the accumulator, log function, and final addition need their own precision and range checks.

The sum can grow with class count, so using a low-precision accumulator for an enormous number of terms is not automatically safe just because each term is at most one. Likewise, a true final result outside the destination range cannot be made representable by rearranging it. A carefully implemented library routine can choose suitable intermediate arithmetic and edge-case handling. Consult that operation's actual contract rather than assuming an output dtype tells the whole story. Compare both log-sum-exp and derived probabilities against a reference over shifted and extreme but valid fixtures.

LSE⁡(z)=log⁡∑i=1Kezi=m+log⁡∑i=1Kezi−m,m=max⁡izi\operatorname{LSE}(z)=\log\sum_{i=1}^{K}e^{z_i}=m+\log\sum_{i=1}^{K}e^{z_i-m},\qquad m=\max_i z_i
The identity is for K positive and finite real logits z_i. Logits and the natural logarithm's arguments are dimensionless. Shifted exponentials are in (0,1] mathematically, but finite-precision underflow, sum range, and exceptional input handling remain implementation concerns.↔ Scroll wide equations horizontally.

Compute the loss in log space when possible

For a target class y, cross-entropy is log-sum-exp minus its target logit. A useful evaluation groups the expression as m minus z_y plus the logarithm of the shifted exponential sum. This avoids first rounding a tiny softmax probability to zero and then taking log zero. It can also avoid subtracting two separately rounded large outputs near one another. The same principle motivates combined binary-logit losses that use stable expressions rather than a separately materialized sigmoid followed by logarithms.

For a binary target in zero through one, one stable logit-loss identity uses max(z,0) minus y times z plus log1p(exp(−abs(z))). Here log1p is designed to evaluate log(1+t) accurately for small t. The implementation still needs attention to multiplication and subtraction with exceptional values. An all-masked vector of negative infinities does not satisfy the finite nonempty premise and can make a naive maximum shift produce infinity minus infinity. Define whether such a case is invalid, excluded, or given another explicit application meaning before computing a loss.

ℓy=(m−zy)+log⁡∑iezi−m,ℓbinary(z,y)=max⁡(z,0)−yz+log⁡(1+e−∣z∣)\ell_y=(m-z_y)+\log\sum_i e^{z_i-m},\qquad \ell_{\rm binary}(z,y)=\max(z,0)-yz+\log(1+e^{-|z|})
The multiclass expression uses a valid target index and finite logits. The binary identity uses finite z and target y in [0,1], with the final term preferably evaluated using log1p. These exact identities do not define all-masked or infinite-input semantics, nor guarantee every finite-precision implementation is equally accurate.↔ Scroll wide equations horizontally.

Stable formulas cannot restore rounded-away inputs

If two distinct logits already became identical in a coarse input representation, shifting them afterward cannot recover their original gap. Test input casting separately from the stable evaluation. Check the loss and its gradients, because a finite plausible scalar does not establish useful gradient accuracy. Include nearly equal large logits, one strongly dominant class, many classes, and explicitly invalid or masked cases. Preserve the same target and masking semantics in the reference rather than comparing two implementations of different mathematical functions.

The sigmoid lab shows the moderate-logit function only. Reset, set both input x=1 and weight w=2, predict logit 1.5 and output about 0.818, then Play or Step. Reset and re-enter both x=1 and w=−2 to predict logit −2.5 and output about 0.076. Its fixed graph is sigmoid(wx−0.5), and playback traces the computation rather than training it. It uses no selectable low-precision format and does not reproduce exponential overflow, loss computation, all-masked inputs, or gradient accuracy. Use the worked log-space calculation to study those numerical questions.

A shifted three-class loss avoids huge exponentials

Use dimensionless logits [80,79,−80] and target class index one, whose logit is 79. Compute a reference cross-entropy using the maximum shift, without directly evaluating exp(80).

  1. Choose m=80. Shifted logits are [0,−1,−160], so the exponential sum is 1 + exp(−1) + exp(−160), approximately 1.3678794412.

  2. The logarithm of that sum is approximately 0.3132616875. Thus log-sum-exp is about 80.3132616875, without forming the enormous original exponentials.

  3. Group the target loss as (80−79)+0.3132616875, giving about 1.3132616875. The target softmax probability is about 0.2689414214; computing the loss directly avoids a separate probability-to-log rounding path.

The result

The shifted reference loss is about 1.31326. In a real low-precision path, use the documented stable operation and check its inputs, accumulation, masks, and gradients separately.

Explore the model

Interactive lab

Interactive lab · network

Inspect a moderate sigmoid logit

Reset, set both x=1 and w=2, predict logit 1.5 and sigmoid about 0.818, then Play or Step. Reset and re-enter x=1 and w=−2 for logit −2.5 and output about 0.076. The fixed sigmoid(wx−0.5) graph has no selectable dtype, loss, training, overflow, or mask handling; playback only traces the selected computation.

Inspect a moderate sigmoid logitOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA nonlinear function's mathematical graph and the numerical stability of a loss implementation require different evidence.

Check your understanding

Why is a direct log-softmax or stable combined cross-entropy preferable to taking the logarithm of a separately rounded tiny probability?

Try it yourself

For two finite logits [20,20] and either target class, compute shifted log-sum-exp and cross-entropy. Explain why neither requires evaluating exp(20) directly.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Subtract the common maximum and keep the loss grouped in shifted form.

Compare with the solution

The shifted logits are zero and zero, so their exponential sum is two. Log-sum-exp is 20 + log(2) ≈20.6931471806, and target cross-entropy is (20−20)+log(2) ≈0.6931471806. The transformation uses exponentials of zero; a real implementation still needs valid input representation and suitable sum/log arithmetic.

Take it with you

  • Maximum shifting controls exponential magnitudes for nonempty finite logit vectors.
  • Direct log-space losses avoid an unnecessary tiny-probability intermediate.
  • Stable identities require explicit masks, exceptional-value domains, and earlier-cast checks.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.