27 / 90

Day 27: Information Theory: Entropy, Cross-Entropy, and Language-Model Loss

Measure surprisal in bits and nats, compute entropy and cross-entropy by hand, and connect cross-entropy to next-token negative log-likelihood and perplexity with explicit numerical-stability safeguards.

Mathematics & Algorithmic Foundations 480 active minutes (8 hours focused study)
01 120 min

Logarithms, surprisal, and units of information

Assistance allowed only after prediction and observed evidence are recorded.

Prerequisites

Complete Day 26 (random variables and sampling); use the listed recovery link (Day 21) if blocked.

Learning Objective

Interpret $-\log p$ as the surprisal (information content) of an outcome, convert between bits ($\log_2$) and nats ($\ln$), and handle $\log(0)$ safely.

Instructions

The Shannon information content of an outcome with probability $p$ is $-\log_2 p$ bits, or $-\ln p$ nats; 1 bit $= \ln 2 \approx 0.6931$ nats. Rarer outcomes carry more information. As a limit $\log p \to -\infty$ as $p \to 0^+$ (the extended-real convention writes $\log(0) = -\infty$) — a limit convention, not an API guarantee: in this environment's Python standard library math.log(0) and math.log1p(-1) raise ValueError, and other numeric libraries may behave differently. Implementations therefore clip probabilities ($p \leftarrow \max(p,\varepsilon)$) or - for arguments near 1 only - use math.log1p(x) = ln(1+x) so log1p(p-1) computes ln p precisely; a distinct p=0 policy is still required (clip to a positive floor, smooth probabilities, or explicitly accept infinite loss) - naming log1p alone is not a zero-probability safeguard.

Practice & Prediction Log

Build a surprisal table in bits and nats for $p\in\{0.5,0.25,0.125,0.8,0.1\}$. Then convert 2 bits to nats and explain why $-\ln(0.1)\approx2.3026$ is about ten times $-\ln(0.8)\approx0.2231$.

Independent Mastery Criterion

Your table matches the verified values in both units, and you state the $\log(0)$ failure plus one concrete safeguard (clipping/a positive floor, or log1p for p near 1 only) plus a stated p=0 policy (floor, smoothing, or declared infinite loss).

Authoritative Source Resources & Provenance

linking Cambridge University Press copyright; free online reading authorized No text extraction or redistribution permitted

Information Theory, Inference, and Learning Algorithms

Author: David J. C. MacKay | Original Source Link ↗

Relevant Section / Range: Chapter 2: Probability, Entropy, and Inference (Shannon information content)

Verified Version & Date: Cambridge University Press 2003, authorized free PDF (Verified: 2026-10-30)

Selection Rationale:

Freely available textbook introducing surprisal -log p with worked numerical exercises.

Source Prerequisites:

Probability foundations (Day 25-26)

Safe Fallback (Offline Resilience):

All required definitions, tables, and worked answers are reproduced locally in this lesson.

Compared Candidate Sources & Selection Analysis (3)
Cover & Thomas, Elements of Information Theory ↗ compared_alternative [Wiley copyright]

The standard rigorous reference; paywalled, so it is cited alongside MacKay only via linking rather than as the sole learner-facing text.

James V. Stone, Information Theory: A Tutorial Introduction ↗ compared_alternative [Open Access / CC BY-NC-SA 4.0]

Gentler introduction freely readable on arXiv; less depth on coding and inference connections needed for the language-model-loss bridge.

Shannon, A Mathematical Theory of Communication (1948) ↗ compared_alternative [Bell System Technical Journal copyright]

Historical primary source; valuable citation but dated notation makes it supplementary rather than primary for learners.

linking PSF License Version 2

Python 3 math: Mathematical functions

Author: Python Software Foundation | Original Source Link ↗

Relevant Section / Range: math.log, math.log2, math.log1p (log bases and near-zero precision)

Verified Version & Date: Python 3.12 documentation (Verified: 2026-10-30)

Selection Rationale:

Normative reference for the log-base and log1p calls used in the surprisal table.

Source Prerequisites:

Basic Python syntax

Safe Fallback (Offline Resilience):

Use the installed interpreter's help(math) and the included deterministic commands.

Compared Candidate Sources & Selection Analysis (2)
NumPy log and ufunc documentation ↗ compared_deferred [BSD 3-Clause]

Vectorized logs arrive with the tensor track; scalar math functions keep Day 27 dependency-free.

decimal — Decimal fixed point and floating point arithmetic ↗ compared_alternative [PSF License Version 2]

Decimal-precision reference rather than binary float math; math remains the correct module for the operators and constants these days use.

02 120 min

Entropy of a distribution

Independent Mastery Check (no AI assistance).

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Compute Shannon entropy $H(X)=-\sum_x p(x)\log_2 p(x)$ and interpret it as expected surprisal, i.e. the ideal average code length.

Instructions

Entropy depends only on the probability values, not on the labels or the numeric outcomes. Required work: compute both entropies below unaided, compare them, and state the units.

Practice & Prediction Log

(a) Compute $H(X)$ for $p=[0.5,0.25,0.125,0.125]$. (b) Compute $H$ for a fair six-sided die. (c) Which distribution is more uncertain, and does entropy depend on the outcome values $\{0,1,2,3\}$ or only on $p$?

Independent Mastery Criterion

Both entropies are computed unaided with correct units, and you state that entropy is a property of the probability vector alone.

Authoritative Source Resources & Provenance

linking Cambridge University Press copyright; free online reading authorized No text extraction or redistribution permitted

Information Theory, Inference, and Learning Algorithms

Author: David J. C. MacKay | Original Source Link ↗

Relevant Section / Range: Chapter 2: Shannon information content and entropy; Chapter 4 (source coding theorem)

Verified Version & Date: Cambridge University Press 2003, authorized free PDF (Verified: 2026-10-30)

Selection Rationale:

Authorized-free textbook derivations of entropy as expected surprisal and ideal code length.

Source Prerequisites:

Probability foundations (Day 25-26)

Safe Fallback (Offline Resilience):

All required definitions, tables, and worked answers are reproduced locally in this lesson.

Compared Candidate Sources & Selection Analysis (3)
Cover & Thomas, Elements of Information Theory ↗ compared_alternative [Wiley copyright]

The standard rigorous reference; paywalled, so it is cited alongside MacKay only via linking rather than as the sole learner-facing text.

James V. Stone, Information Theory: A Tutorial Introduction ↗ compared_alternative [Open Access / CC BY-NC-SA 4.0]

Gentler introduction freely readable on arXiv; less depth on coding and inference connections needed for the language-model-loss bridge.

Shannon, A Mathematical Theory of Communication (1948) ↗ compared_alternative [Bell System Technical Journal copyright]

Historical primary source; valuable citation but dated notation makes it supplementary rather than primary for learners.

linking Wiley copyright / Academic linking only No text extraction or distribution permitted

Elements of Information Theory

Author: Thomas M. Cover, Joy A. Thomas | Original Source Link ↗

Relevant Section / Range: Chapter 2: Entropy, Relative Entropy, and Mutual Information

Verified Version & Date: 2nd Edition, Wiley 2006 (Verified: 2026-10-30)

Selection Rationale:

Detailed mathematical reference for entropy properties cited alongside the free MacKay text.

Source Prerequisites:

Probability foundations and logarithms

Safe Fallback (Offline Resilience):

Self-contained derivations in activity instructions and offline guide.

Compared Candidate Sources & Selection Analysis (2)
David MacKay, Information Theory, Inference, and Learning Algorithms ↗ compared_alternative [Cambridge University Press copyright; free online reading authorized]

Co-selected: equally rigorous and freely readable online, so it carries the primary learner-facing role.

Dive into Deep Learning: Information Theory appendix ↗ compared_alternative [CC BY-SA 4.0 (book text) / modified MIT (sample code)]

Code-integrated deep-learning framing; useful supplementary reading but less mathematically complete for entropy proofs.

03 120 min

Cross-entropy, KL divergence, and language-model loss

Assistance allowed only after prediction and observed evidence are recorded.

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Compute cross-entropy $H(p,q)=-\sum_x p(x)\log_2 q(x)$ and KL divergence $D_{KL}(p\|q)=H(p,q)-H(p)$; connect them to next-token NLL loss and perplexity, including the zero-probability failure and KL asymmetry.

Instructions

When the true distribution is $p$ and the model says $q$, the expected coding cost is $H(p,q)$; the excess over $H(p)$ is $D_{KL}(p\|q)\ge0$. Language-model training minimizes exactly this: for each observed token the loss is $-\ln q(\text{token})$, and perplexity is $e^{\text{mean NLL}}$. Compute each quantity below before running code.

Practice & Prediction Log

With $p=[0.5,0.25,0.125,0.125]$: (a) compute $H(p,q)$ and $D_{KL}(p\|q)$ for uniform $q=[0.25,0.25,0.25,0.25]$; (b) for $q=[0.4,0.3,0.15,0.15]$ compute $D_{KL}(p\|q)$ and $D_{KL}(q\|p)$ - are they equal? (c) A language model assigns $q=0.8, 0.5, 0.25$ to the next three true tokens: compute mean NLL and perplexity. (d) What happens to corpus loss if the model assigns $q=0$ to one observed token?

Independent Mastery Criterion

Cross-entropy and both KL directions are computed by hand; you explain the NLL = per-token $-\ln q$ identity, give perplexity as an exponentiated mean, and name the zero-probability failure and one safeguard.

Authoritative Source Resources & Provenance

linking Wiley copyright / Academic linking only No text extraction or distribution permitted

Elements of Information Theory

Author: Thomas M. Cover, Joy A. Thomas | Original Source Link ↗

Relevant Section / Range: Chapter 2: relative entropy (KL divergence) and its non-negativity

Verified Version & Date: 2nd Edition, Wiley 2006 (Verified: 2026-10-30)

Selection Rationale:

Standard reference for D_KL(p||q) definitions and asymmetry used in this activity.

Source Prerequisites:

Probability foundations and logarithms

Safe Fallback (Offline Resilience):

Self-contained derivations in activity instructions and offline guide.

Compared Candidate Sources & Selection Analysis (2)
David MacKay, Information Theory, Inference, and Learning Algorithms ↗ compared_alternative [Cambridge University Press copyright; free online reading authorized]

Co-selected: equally rigorous and freely readable online, so it carries the primary learner-facing role.

Dive into Deep Learning: Information Theory appendix ↗ compared_alternative [CC BY-SA 4.0 (book text) / modified MIT (sample code)]

Code-integrated deep-learning framing; useful supplementary reading but less mathematically complete for entropy proofs.

linking Cambridge University Press copyright; free online reading authorized No text extraction or redistribution permitted

Information Theory, Inference, and Learning Algorithms

Author: David J. C. MacKay | Original Source Link ↗

Relevant Section / Range: Chapters 2 and 5: cross-entropy ideas, symbol codes, and noisy-channel models

Verified Version & Date: Cambridge University Press 2003, authorized free PDF (Verified: 2026-10-30)

Selection Rationale:

Authorized-free bridge from coding theory to probabilistic models used for the LM-loss connection.

Source Prerequisites:

Probability foundations (Day 25-26)

Safe Fallback (Offline Resilience):

All required definitions, derivations, and worked answers are reproduced locally in this lesson.

Compared Candidate Sources & Selection Analysis (3)
Cover & Thomas, Elements of Information Theory ↗ compared_alternative [Wiley copyright]

The standard rigorous reference; paywalled, so it is cited alongside MacKay only via linking rather than as the sole learner-facing text.

James V. Stone, Information Theory: A Tutorial Introduction ↗ compared_alternative [Open Access / CC BY-NC-SA 4.0]

Gentler introduction freely readable on arXiv; less depth on coding and inference connections needed for the language-model-loss bridge.

Shannon, A Mathematical Theory of Communication (1948) ↗ compared_alternative [Bell System Technical Journal copyright]

Historical primary source; valuable citation but dated notation makes it supplementary rather than primary for learners.

04 120 min

Independent mastery check: information-theoretic losses

Independent Mastery Check (no AI assistance).

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Compute entropy, cross-entropy, KL, NLL, and perplexity unaided on a fresh distribution, and state the numerical safeguards.

Instructions

No AI or references during this check. Record predictions, compute all four items, then review and pick a recovery link for any miss. Preserve the first unaided attempt unchanged; afterwards, error review and any assisted recovery are a distinct phase. A missed idea is not remediated merely by review or a retake: it requires a genuinely fresh equivalent unaided check whose answer is not shown in advance. The supplied second check is a post-remediation self-check, not fresh unseen evidence. Second check (only after remediation; unaided, no hints): Before starting, close the answer/reference and do not read or run the checker during this attempt. Complete it unaided and without hints. Reviewing formulas learned during prior remediation is concept review, not display of the second numerical answer. (a) Compute $H(p)$ for $p=[0.55,0.20,0.15,0.10]$. (b) Compute $H(p,q)$ and $D_{KL}(p\|q)$ against uniform $q$ over the four types. (c) For tokens scored $q=[0.25,0.5,0.2]$ compute per-token NLL, mean NLL, and perplexity. (d) If one more observed token is scored $q=0$, what happens to the mean NLL, and which safeguard prevents it? After completing the attempt, preserve the second unaided submission unchanged before opening or running the checker. Then use its direct numeric feedback only for (a), (b), and (c) as post-remediation self-check evidence, and only if the checker was neither read nor run during that attempt and the submission was preserved unchanged first; it reports pass/fail only for those parts. Assess (d) manually after the attempt using the separate post-attempt rubric in the answer: because it repeats the zero-probability idea already stated in the initial prompt/reference, this is manual review/re-explanation, not a new unseen assessment. If (d) is missed, it remains not independently revalidated until a genuinely fresh equivalent (d) task whose answer is not shown in advance is provided and passed unaided; no such new (d) task is supplied here. Then use the independent identities as additional cross-checks, not substitutes for the direct checking ($H(p,q)=H(p)+D_{KL}(p\|q)$ with $D_{KL}\ge0$; perplexity equals the inverse geometric mean of the token probabilities). Feedback retakes are remediation, not a new unaided first pass. Timing, preservation, unaided conduct, and deliberate premature checker execution are policy-only; no hidden UI enforcement exists. Remediate a missed (a) with day-27-act-01 (surprisal, log units) and day-27-act-02 (entropy), (b)-(c) with day-27-act-03 (cross-entropy, KL, NLL, perplexity), and (d) with day-27-act-01 (safe $\log 0$ handling) and day-27-act-03 (zero-probability failure).

Practice & Prediction Log

(a) Compute $H(p)$ for $p=[0.4,0.3,0.2,0.1]$. (b) Compute $H(p,q)$ and $D_{KL}(p\|q)$ against uniform $q$ over the four types. (c) For tokens scored $q=[0.5,0.4,0.1]$ compute per-token NLL, mean NLL, and perplexity. (d) Why does a single observed token with $q=0$ force infinite corpus loss, and name one fix.

Independent Mastery Criterion

The unaided numeric results must match the corresponding reference values within the stated absolute tolerance of 0.00005 (half of one four-decimal unit); explain why one observed token with $q=0$ forces infinite corpus loss and give a concrete fix. Preserve that attempt unchanged, keeping error review and assisted recovery separate. Use the preserved, unaided post-remediation self-check for (a), (b), and (c) only as direct numeric evidence when the checker was neither read nor run during that attempt and the submission was preserved first; the corresponding reference values must match within the stated absolute tolerance of 0.00005 (half of one four-decimal unit). The supplied (d) repeats the zero-probability idea from the initial prompt/reference, so its result is manual review/re-explanation, not new unseen evidence. If (d) is missed, it remains not independently revalidated until a genuinely fresh equivalent (d) task whose answer is not shown in advance is supplied and passed unaided; no such task is supplied here. Misses route to a recovery link; feedback retakes are remediation, not a new unaided first pass. Timing, preservation, unaided conduct, and deliberate premature checker execution are policy-only; no hidden UI enforcement exists.

Authoritative Source Resources & Provenance

linking Cambridge University Press copyright; free online reading authorized No text extraction or redistribution permitted

Information Theory, Inference, and Learning Algorithms

Author: David J. C. MacKay | Original Source Link ↗

Relevant Section / Range: Chapters 2 and 4 review: entropy and source coding exercises

Verified Version & Date: Cambridge University Press 2003, authorized free PDF (Verified: 2026-10-30)

Selection Rationale:

Authorized-free exercise coverage aligned with this day's assessment scope.

Source Prerequisites:

Probability foundations (Day 25-26)

Safe Fallback (Offline Resilience):

The assessment is self-contained with original items and worked reference answers.

Compared Candidate Sources & Selection Analysis (3)
Cover & Thomas, Elements of Information Theory ↗ compared_alternative [Wiley copyright]

The standard rigorous reference; paywalled, so it is cited alongside MacKay only via linking rather than as the sole learner-facing text.

James V. Stone, Information Theory: A Tutorial Introduction ↗ compared_alternative [Open Access / CC BY-NC-SA 4.0]

Gentler introduction freely readable on arXiv; less depth on coding and inference connections needed for the language-model-loss bridge.

Shannon, A Mathematical Theory of Communication (1948) ↗ compared_alternative [Bell System Technical Journal copyright]

Historical primary source; valuable citation but dated notation makes it supplementary rather than primary for learners.

linking Wiley copyright / Academic linking only No text extraction or distribution permitted

Elements of Information Theory

Author: Thomas M. Cover, Joy A. Thomas | Original Source Link ↗

Relevant Section / Range: Chapter 2 review problems: entropy and relative entropy

Verified Version & Date: 2nd Edition, Wiley 2006 (Verified: 2026-10-30)

Selection Rationale:

Reference for entropy and KL identities this assessment checks without assistance.

Source Prerequisites:

Probability foundations and logarithms

Safe Fallback (Offline Resilience):

The assessment is self-contained with original items and worked reference answers.

Compared Candidate Sources & Selection Analysis (2)
David MacKay, Information Theory, Inference, and Learning Algorithms ↗ compared_alternative [Cambridge University Press copyright; free online reading authorized]

Co-selected: equally rigorous and freely readable online, so it carries the primary learner-facing role.

Dive into Deep Learning: Information Theory appendix ↗ compared_alternative [CC BY-SA 4.0 (book text) / modified MIT (sample code)]

Code-integrated deep-learning framing; useful supplementary reading but less mathematically complete for entropy proofs.