Mathematical Foundations

VII.7 · Information Theory

Which part of a tiny probability can remain finite?

Follow the actual maximum, shifted scores, exponentials, denominator and log probabilities. Compare naive overflow, probability underflow and explicit domain policies.

The stable numerical pipeline

Explorer: Actual max-shift, exponential and log-probability stages
ClassInput zz − mexp(z − m)Stable log pStable p
120≈ 1≈ -0.407606≈ 0.665241
21-1≈ 0.367879≈ -1.40761≈ 0.244728
30-2≈ 0.135335≈ -2.40761≈ 0.0900306
Stable output probabilities
  1. Class 1 probability: ≈ 0.665241
  2. Class 2 probability: ≈ 0.244728
  3. Class 3 probability: ≈ 0.0900306

Bar length = absolute contribution on a shared scale; sign and infinities appear in the labels.

Logits are scores, not probabilities. Input +∞ and NaN are rejected; an explicit −∞ excludes a class. All −∞ has no normalizable mass. Finite logits can still have numerical underflow.

Effective logits [2, 1, 0]. m=2; shifted exponentials [≈ 1, ≈ 0.367879, ≈ 0.135335]; denominator ≈ 1.50321. Stable sum ≈ 1; normalization error ≈ 1.11022e-16 ≤ ≈ 4.26326e-14 budget. Naive path: finite.

Maximum input logit
2
Shifted exponential denominator
1.503215
Stable log-sum-exp
2.407606
Selected class probability
0.665241
Selected stable log probability
−0.407606
Naive binary64 denominator
11.107338
Normalization error
1.11022×10⁻¹⁶
Common-shift probability difference
0

= exact rational or mathematical boundary · ≈ approximate binary64 evaluation

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from 0 to 2, whole numbers only

Effective logits [2, 1, 0]. m=2; shifted exponentials [≈ 1, ≈ 0.367879, ≈ 0.135335]; denominator ≈ 1.50321. Stable sum ≈ 1; normalization error ≈ 1.11022e-16 ≤ ≈ 4.26326e-14 budget. Naive path: finite. Common-shift probability difference ≈ 0.

m=max⁡izi,log⁡∑iezi=m+log⁡∑iezi−mm=\max_i z_i,\quad\log\sum_i e^{z_i}=m+\log\sum_i e^{z_i-m}
log⁡pi=(zi−m)−log⁡∑jezj−m\log p_i=(z_i-m)-\log\sum_j e^{z_j-m}
softmax⁡(z+c1)=softmax⁡(z)\operatorname{softmax}(\mathbf z+c\mathbf1)=\operatorname{softmax}(\mathbf z)

Find and subtract the actual maximum

m=2. Shifted logits [0, -1, -2].

z~i=zi−m\widetilde z_i=z_i-m

Follow the actual maximum, shifted scores, exponentials, denominator and log probabilities. Compare naive overflow, probability underflow and explicit domain policies.

Intuition

A score offset can make every direct exponential enormous or tiny while leaving relative probabilities unchanged. Removing that common scale protects normalization. A very small final probability can still underflow, but its logarithm can be computed without constructing that tiny number.

Definition

For a nonempty score vector with at least one finite entry, let m=max⁡izim=\max_i z_i. Then LSE⁡(z)=log⁡∑iezi=m+log⁡∑iezi−m\operatorname{LSE}(\mathbf z)=\log\sum_i e^{z_i}=m+\log\sum_i e^{z_i-m} and log⁡pi=zi−LSE⁡(z)\log p_i=z_i-\operatorname{LSE}(\mathbf z). Compute the latter equivalently as (zi−m)−log⁡∑jezj−m(z_i-m)-\log\sum_j e^{z_j-m} to keep the correction after centering.

Mechanics

The table shows the actual input z, subtraction z−m, shifted exp, stable log probability and final probability for every class. The inspector displays the actual maximum, denominator, LSE and normalization residual. The naive denominator remains visible as a separate computation. Boundary presets present their actual exceptional vector; the model reports its policy without generating unrelated predictions.

Derivation

Factor out eme^m from the exponential sum. Taking log yields m+log⁡∑iezi−mm+\log\sum_i e^{z_i-m}. Every finite shifted score is at most zero, at least one is zero, and the shifted denominator lies in [1,n]. Thus unnecessary exponential overflow disappears. For log-softmax, algebraically subtract the correction after centering; this avoids subtracting two huge rounded values. Computing log⁡\log of a final rounded probability would discard information already present in the scores.

Worked examples

At (1000,999,998), m=1000, shifted scores (0,−1,−2), shifted exponentials (1,e−1,e−2)(1,e^{-1},e^{-2}), denominator approximately 1.503215 and LSE approximately 1000.407606. At (1000,0,−1000), final binary64 probabilities are (1,0,0), but stable log probabilities remain (0,−1000,−2000). At two equal scores near 1030810^{308}, the rounded LSE equals the common score; the centered log probabilities still equal −log⁡2-\log2.

Worked example: The stable numerical pipeline

Worked example: Actual max-shift, exponential and log-probability stages
ClassInput zz − mexp(z − m)Stable log pStable p
120≈ 1≈ -0.407606≈ 0.665241
21-1≈ 0.367879≈ -1.40761≈ 0.244728
30-2≈ 0.135335≈ -2.40761≈ 0.0900306
Stable output probabilities
  1. Class 1 probability: ≈ 0.665241
  2. Class 2 probability: ≈ 0.244728
  3. Class 3 probability: ≈ 0.0900306

Bar length = absolute contribution on a shared scale; sign and infinities appear in the labels.

Logits are scores, not probabilities. Input +∞ and NaN are rejected; an explicit −∞ excludes a class. All −∞ has no normalizable mass. Finite logits can still have numerical underflow.

Effective logits [2, 1, 0]. m=2; shifted exponentials [≈ 1, ≈ 0.367879, ≈ 0.135335]; denominator ≈ 1.50321. Stable sum ≈ 1; normalization error ≈ 1.11022e-16 ≤ ≈ 4.26326e-14 budget. Naive path: finite.

Maximum input logit
2
Shifted exponential denominator
1.503215
Stable log-sum-exp
2.407606
Selected class probability
0.665241
Selected stable log probability
−0.407606
Naive binary64 denominator
11.107338
Normalization error
1.11022×10⁻¹⁶
Common-shift probability difference
0

= exact rational or mathematical boundary · ≈ approximate binary64 evaluation

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from −1000 to 1000, up to 2 decimal places

from 0 to 2, whole numbers only

Effective logits [2, 1, 0]. m=2; shifted exponentials [≈ 1, ≈ 0.367879, ≈ 0.135335]; denominator ≈ 1.50321. Stable sum ≈ 1; normalization error ≈ 1.11022e-16 ≤ ≈ 4.26326e-14 budget. Naive path: finite. Common-shift probability difference ≈ 0.

m=max⁡izi,log⁡∑iezi=m+log⁡∑iezi−mm=\max_i z_i,\quad\log\sum_i e^{z_i}=m+\log\sum_i e^{z_i-m}
log⁡pi=(zi−m)−log⁡∑jezj−m\log p_i=(z_i-m)-\log\sum_j e^{z_j-m}
softmax⁡(z+c1)=softmax⁡(z)\operatorname{softmax}(\mathbf z+c\mathbf1)=\operatorname{softmax}(\mathbf z)

Find and subtract the actual maximum

m=2. Shifted logits [0, -1, -2].

z~i=zi−m\widetilde z_i=z_i-m

Replay actual scores, normalization, log probabilities and the selected result.

Executable reference code

The standalone pedagogical implementation exposes the operations. Its NumPy companion uses array reductions and explicit domain/mask guards. Both include assertions for the hand-worked examples.

code/python/information_stability.py
"""Expose every stable stage; retain centered log-softmax corrections."""
from math import exp,log,fsum,isfinite,inf
def pipeline(logits):
    if not 1<=len(logits)<=6 or any(not isfinite(z) and z!=-inf for z in logits):raise ValueError('Invalid logits')
    m=max(logits)
    if m==-inf:raise ValueError('All −infinity: no normalizable mass')
    shifted=[z-m for z in logits]
    exponentials=[exp(z) for z in shifted]
    denominator=fsum(exponentials);correction=log(denominator)
    log_probabilities=[z-correction for z in shifted]
    probabilities=[e/denominator for e in exponentials]
    return dict(max=m,shifted=shifted,exponentials=exponentials,denominator=denominator,logsumexp=m+correction,log_probabilities=log_probabilities,probabilities=probabilities)
if __name__=='__main__':
    d=pipeline([1000,0,-1000]);assert d['log_probabilities']==[0,-1000,-2000]
    assert d['probabilities']==[1,0,0]
    assert pipeline([1e308,1e308])['log_probabilities']==[-log(2),-log(2)]
    assert pipeline([0,-inf])['log_probabilities']==[0,-inf]
    print(pipeline([1000,0,-1000]))
code/python/information_stability_numpy.py
"""Stable logsumexp and logsoftmax; logs do not take log of rounded probabilities."""
import numpy as np
def pipeline(logits):
    z=np.asarray(logits,dtype=float)
    if z.ndim!=1 or not 1<=z.size<=6 or np.any(np.isnan(z)) or np.any(z==np.inf):raise ValueError('Invalid logits')
    m=z.max()
    if m==-np.inf:raise ValueError('All excluded: normalization undefined')
    with np.errstate(over='ignore',under='ignore'):shifted=z-m;e=np.exp(shifted)
    denominator=e.sum();correction=np.log(denominator)
    return m+correction,shifted-correction,e/denominator
if __name__=='__main__':
    lse,lp,p=pipeline([1000,0,-1000]);assert np.array_equal(lp,[0,-1000,-2000]);assert np.array_equal(p,[1,0,0])
    assert np.array_equal(pipeline([1e308,1e308])[1],[-np.log(2),-np.log(2)])
    print(pipeline([1000,0,-1000]))

Explore

Select Overflow + tiny probability and identify every actual intermediate value. Next select Naive denominator underflows: the stable result still normalizes. Select One excluded class, All −∞, Reject +∞, Reject NaN and Empty vector; explain why they are different mathematical policies. Huge equal finite logits verifies that the log correction survives a huge common offset.

Common mistakes and counterexamples

Stabilization cannot guarantee that every tiny output probability is representable. Numerical probability zero from finite scores does not mean impossible support. A mathematical −∞ input explicitly excludes a class. All −∞ has a zero denominator and no unique distribution; inventing uniform probabilities would silently change the model. Positive infinity and NaN are rejected here rather than assigned an arbitrary limiting rule.

Numerical considerations

Empty vectors, more than six entries, NaN and +∞ are invalid. An isolated −∞ is accepted as excluded support; all −∞ is undefined. Finite max-shift subtraction can itself exceed binary64 range at extreme opposite scores; that −∞ log result is labeled numerical range loss, not mathematical impossibility. Stable output comes from the evaluated max-shift algorithm. Direct exponential normalization with 400-digit Decimal arithmetic provides an independent comparison for feasible scores; analytic equal/dominant identities provide references for enormous-score examples. Logs use a 2e−12 scaled absolute/relative comparison tolerance; probabilities use 2e−14 absolute error. Normalization budget is 32×epsilon×6. These are numerical allowances, not proofs of analytic identities.

Engineering and ML connections

Log-softmax lets a classifier or language model compute a finite NLL for a token whose displayed probability underflows. The next chapter selects the target’s stable log probability directly. Numerical stability changes the evaluation of the same mathematical model; it does not authorize smoothing impossible events.

Connect to softmax normalization.

Exercises

Predict intermediate quantities, calculate small cases and explain numerical or mask boundaries.

calculation

Actual max shift

For logits (1000,999,998), give m and the three shifted logits.

calculation

Equal log probabilities

For two equal logits, what is their common log probability in bits?

prediction

Probability underflow

Stable softmax at (1000,0,−1000) rounds the last probability to zero. What is its stable log probability?

Choose one answer

explanation

All excluded

What is the normalized prediction for (−∞,−∞)?

Choose one answer

construction

Keep the correction

With two equal logits near 10³⁰⁸, why use (zᵢ−m)−log denominator for log-softmax?

Choose one answer

Summary and checkpoints

A score offset can make every direct exponential enormous or tiny while leaving relative probabilities unchanged. Removing that common scale protects normalization. A very small final probability can still underflow, but its logarithm can be computed without constructing that tiny number. Read the actual pipeline, preserve the log information and state which inputs contribute.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available