Mathematical Foundations

VII.8 · Information Theory

How does the next-token prediction become one scalar loss?

Select a sequence position, inspect its four vocabulary logits, choose the observed target token and reduce stable token losses over explicit unmasked positions.

Vocabulary prediction → observed-token loss

Explorer: Actual vocabulary pipeline at position 1
TokenLogitz − maxShifted expStable log pProbabilityOne-hot loss term
the · target20≈ 1≈ -0.185182≈ 0.830953≈ 0.185182
cat0-2≈ 0.135335≈ -2.18518≈ 0.112457≈ 0
sat-1-3≈ 0.0497871≈ -3.18518≈ 0.0413707≈ 0
<eos>-2-4≈ 0.0183156≈ -4.18518≈ 0.0152194≈ 0
This position’s actual vocabulary probabilities
  1. the probability: ≈ 0.830953
  2. cat probability: ≈ 0.112457
  3. sat probability: ≈ 0.0413707
  4. <eos> probability: ≈ 0.0152194

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

Explorer: Actual position losses and reduction mask
PositionTargetNLL (nats)Contributes?
1the≈ 0.185182Yes
2cat≈ 0.185182Yes
3sat≈ 0.44019Yes
4<eos>≈ 0.185182Yes

Vocabulary: the, cat, sat, <eos>. These are explicit toy labels and supplied scores; no tokenizer or transformer is running. The mean denominator counts only unmasked positions.

Position 1: target the. Actual logits [2, 0, -1, -2]; target log probability ≈ -0.185182; NLL ≈ 0.185182 nats. This position contributes to the aggregate. Contributing count 4; total ≈ 0.995737; mean ≈ 0.248934 nats. Mean uses exactly the contributing positions.

Selected target-token NLL (nats)
0.185182
One-hot cross entropy (nats)
0.185182
Contributing positions
4
Contributing loss total (nats)
0.995737
Mean token loss (nats)
0.248934

= 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

Position 1: target the. Actual logits [2, 0, -1, -2]; target log probability ≈ -0.185182; NLL ≈ 0.185182 nats. This position contributes to the aggregate. Contributing count 4; total ≈ 0.995737; mean ≈ 0.248934 nats. Mean uses exactly the contributing positions.

Lt=log⁡∑iezt,i−zt,yt=−log⁡pt,ytL_t=\log\sum_i e^{z_{t,i}}-z_{t,y_t}=-\log p_{t,y_t}
L‾=1∣U∣∑t∈ULt(∣U∣>0)\overline L=\frac{1}{|U|}\sum_{t\in U}L_t\quad(|U|>0)

Read this position’s vocabulary scores

Vocabulary [the, cat, sat, <eos>]. Target the; logits [2, 0, -1, -2].

zt=(zt,1,…,zt,4)\mathbf z_t=(z_{t,1},\ldots,z_{t,4})

Select a sequence position, inspect its four vocabulary logits, choose the observed target token and reduce stable token losses over explicit unmasked positions.

Intuition

At each position a model assigns scores to possible next tokens. The actual target selects one probability from that vocabulary distribution. Its negative log probability is the position’s loss. A sequence loss averages those actual losses, counting only the positions explicitly included.

Definition

Use vocabulary V={the,cat,sat,eos}V=\{\mathrm{the},\mathrm{cat},\mathrm{sat},\mathrm{eos}\}. Position t has supplied logits zt,iz_{t,i} and observed target index yty_t. Its NLL is Lt=−log⁡softmax⁡(zt)yt=LSE⁡(zt)−zt,ytL_t=-\log\operatorname{softmax}(\mathbf z_t)_{y_t}=\operatorname{LSE}(\mathbf z_t)-z_{t,y_t}. If U is the set of unmasked positions, L‾=(1/∣U∣)∑t∈ULt\overline L=(1/|U|)\sum_{t\in U}L_t for ∣U∣>0|U|>0. When U is empty, mean loss is undefined.

Mechanics

The explicit vocabulary is the, cat, sat and <eos>. Position buttons select which actual vector and target to inspect. Numeric score controls and Target token update that selected position. Ignore selected position changes its explicit mask; the sequence table shows all individual losses and inclusion flags. The aggregate count, total and mean derive from those same rows.

Derivation

Stable log-softmax gives log⁡pt,i=(zt,i−mt)−log⁡∑jezt,j−mt\log p_{t,i}=(z_{t,i}-m_t)-\log\sum_j e^{z_{t,j}-m_t}. Negating the target entry yields NLL directly from scores. A one-hot target has exactly one nonzero coefficient, so −∑i1{i=yt}log⁡pt,i=−log⁡pt,yt-\sum_i\mathbf1\{i=y_t\}\log p_{t,i}=-\log p_{t,y_t}. The table shows those actual one-hot terms. For the gradient bridge, differentiating log⁡∑iezi−zy\log\sum_i e^{z_i}-z_y gives ∂L/∂zj=pj−1{j=y}\partial L/\partial z_j=p_j-\mathbf1\{j=y\}; the chain rule connects logits to model parameters.

Worked examples

With four equal logits, every token has probability 1/4 and target NLL is log⁡4≈1.386294\log4\approx1.386294 nats, or 2 bits. For logits (1000,0,−1000,−1000) and target <eos>, probability underflows to zero but NLL remains 2000 nats. If three position losses are (2,4,8) and the middle is masked, count=2 and mean=(2+8)/2=5 nats. An all-masked sequence has total zero and undefined mean.

Worked example: Vocabulary prediction → observed-token loss

Worked example: Actual vocabulary pipeline at position 1
TokenLogitz − maxShifted expStable log pProbabilityOne-hot loss term
the · target20≈ 1≈ -0.185182≈ 0.830953≈ 0.185182
cat0-2≈ 0.135335≈ -2.18518≈ 0.112457≈ 0
sat-1-3≈ 0.0497871≈ -3.18518≈ 0.0413707≈ 0
<eos>-2-4≈ 0.0183156≈ -4.18518≈ 0.0152194≈ 0
This position’s actual vocabulary probabilities
  1. the probability: ≈ 0.830953
  2. cat probability: ≈ 0.112457
  3. sat probability: ≈ 0.0413707
  4. <eos> probability: ≈ 0.0152194

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

Worked example: Actual position losses and reduction mask
PositionTargetNLL (nats)Contributes?
1the≈ 0.185182Yes
2cat≈ 0.185182Yes
3sat≈ 0.44019Yes
4<eos>≈ 0.185182Yes

Vocabulary: the, cat, sat, <eos>. These are explicit toy labels and supplied scores; no tokenizer or transformer is running. The mean denominator counts only unmasked positions.

Position 1: target the. Actual logits [2, 0, -1, -2]; target log probability ≈ -0.185182; NLL ≈ 0.185182 nats. This position contributes to the aggregate. Contributing count 4; total ≈ 0.995737; mean ≈ 0.248934 nats. Mean uses exactly the contributing positions.

Selected target-token NLL (nats)
0.185182
One-hot cross entropy (nats)
0.185182
Contributing positions
4
Contributing loss total (nats)
0.995737
Mean token loss (nats)
0.248934

= 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

Position 1: target the. Actual logits [2, 0, -1, -2]; target log probability ≈ -0.185182; NLL ≈ 0.185182 nats. This position contributes to the aggregate. Contributing count 4; total ≈ 0.995737; mean ≈ 0.248934 nats. Mean uses exactly the contributing positions.

Lt=log⁡∑iezt,i−zt,yt=−log⁡pt,ytL_t=\log\sum_i e^{z_{t,i}}-z_{t,y_t}=-\log p_{t,y_t}
L‾=1∣U∣∑t∈ULt(∣U∣>0)\overline L=\frac{1}{|U|}\sum_{t\in U}L_t\quad(|U|>0)

Read this position’s vocabulary scores

Vocabulary [the, cat, sat, <eos>]. Target the; logits [2, 0, -1, -2].

zt=(zt,1,…,zt,4)\mathbf z_t=(z_{t,1},\ldots,z_{t,4})

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_tokens.py
"""Four supplied vocabulary logits per position; explicit observed target and ignore mask."""
from math import exp,log,fsum,isfinite,inf
VOCABULARY=('the','cat','sat','<eos>')
def mean_loss(positions):
    if not 1<=len(positions)<=4:raise ValueError('Use 1–4 positions')
    losses=[];contributing=[]
    for logits,target,ignored in positions:
        if len(logits)!=4 or type(target) is not int or not 0<=target<4 or type(ignored) is not bool or any((not isfinite(z) and z!=-inf) or (isfinite(z) and abs(z)>1000) for z in logits):raise ValueError('Invalid position')
        m=max(logits)
        if m==-inf:raise ValueError('No normalizable scores')
        shifted=[z-m for z in logits]
        log_denominator=log(fsum(exp(z) for z in shifted))
        loss=log_denominator-shifted[target]
        losses.append(loss)
        if not ignored:contributing.append(loss)
    count=len(contributing);total=fsum(contributing)
    return losses,count,total/count if count else None
if __name__=='__main__':
    p=[([0,0,0,0],2,False),([1000,0,-1000,-1000],3,True)]
    assert mean_loss(p)==([log(4),2000],1,log(4))
    assert mean_loss([(z,y,True) for z,y,_ in p])[2] is None
    print(mean_loss(p))
code/python/information_tokens_numpy.py
"""Array token NLL from centered log-softmax; select contributing rows before summing."""
import numpy as np
VOCABULARY=('the','cat','sat','<eos>')
def mean_loss(logits,targets,ignored):
    z=np.asarray(logits,dtype=float);y=np.asarray(targets);mask=np.asarray(ignored)
    if z.ndim!=2 or z.shape[1]!=4 or not 1<=z.shape[0]<=4 or y.shape!=(z.shape[0],) or mask.shape!=y.shape or mask.dtype!=bool or not np.issubdtype(y.dtype,np.integer) or np.any((y<0)|(y>=4)) or np.any(np.isnan(z)) or np.any(z==np.inf) or np.any(np.isfinite(z)&(np.abs(z)>1000)):raise ValueError('Invalid token batch')
    maxima=z.max(axis=1,keepdims=True)
    if np.any(maxima==-np.inf):raise ValueError('All-excluded position')
    with np.errstate(over='ignore',under='ignore'):shifted=z-maxima;e=np.exp(shifted)
    logp=shifted-np.log(e.sum(axis=1,keepdims=True));losses=-logp[np.arange(y.size),y]
    used=losses[~mask];count=used.size
    return losses,count,float(used.sum()/count) if count else None
if __name__=='__main__':
    losses,count,mean=mean_loss([[0,0,0,0],[1000,0,-1000,-1000]],[2,3],[False,True])
    assert np.array_equal(losses,[np.log(4),2000]) and count==1 and mean==np.log(4)
    assert mean_loss([[0,0,0,0]],[0],[True])[2] is None
    print(losses,count,mean)

Explore

Change position and identify its different logits and target. Switch the observed target without changing the vector and inspect the changed one-hot term. Choose Tiny target probability, finite loss and compare probability zero with finite NLL. Ignore that position and verify the denominator decreases by exactly one. Mask every position, then include them again.

Common mistakes and counterexamples

The target need not be the token with highest predicted probability. Never take log of an underflowed probability when stable log-softmax is available. Masks are explicit; a large loss does not automatically disappear. Mean denominator is the contributing count, not sequence length or vocabulary size. An undefined empty mean is not zero loss.

Numerical considerations

This toy has four named vocabulary entries and one to four supplied positions, with explicit target indices and boolean masks. Invalid targets, vector shapes and undefined predictions are rejected even in ignored positions. Finite scores are bounded to [−1000,1000], with explicit −∞ exclusions allowed by the model. Scores and loss are approximate binary64 quantities. Individual unmasked infinite NLL propagates to the aggregate; masked infinities are skipped before summation rather than multiplied by zero. Stable logs are computed directly from logits, with independent raw Decimal400 references. This is a supplied-score explorer: it has no transformer, tokenizer, external API or network training engine.

Engineering and ML connections

Language-model training evaluates a target token at each contributing sequence position and reduces to a scalar. Given a differentiable score-producing model, the chain rule turns that scalar into parameter gradients. The accepted Optimization update then applies a learning rate to those gradients. This chapter exposes the loss mechanism without implementing a model or optimizer.

Connect to the gradient-descent update.

Exercises

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

calculation

Uniform vocabulary

For four equal vocabulary logits, give target-token NLL in bits.

calculation

Correct mean denominator

Three positions have losses 2,4,8 nats; the middle one is ignored. Give contributing count and mean.

prediction

All masked sequence

What should mean loss report when every position is ignored?

Choose one answer

explanation

Underflow-safe token loss

A target probability rounds to zero but its stable log probability is −2000. What is token NLL?

Choose one answer

construction

Optimization bridge

How does this scalar loss connect to gradient descent?

Choose one answer

Summary and checkpoints

At each position a model assigns scores to possible next tokens. The actual target selects one probability from that vocabulary distribution. Its negative log probability is the position’s loss. A sequence loss averages those actual losses, counting only the positions explicitly included. 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