PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Information Theory and Loss Functions

Intermediate 14 min· 4 exercises

Compute entropy, cross-entropy, KL divergence and perplexity, explain why cross-entropy and mean squared error are the natural losses for classification and regression, and implement softmax, temperature and log-softmax in a numerically stable way.

By the end of this lesson you will be able to
  • Compute self-information, entropy, cross-entropy and KL divergence in bits and nats.
  • Explain why minimizing cross-entropy is equivalent to minimizing KL divergence and to maximum likelihood.
  • Derive the gradient of softmax cross-entropy with respect to the logits.
  • Compute and interpret perplexity for a language model and state its limitations.
  • Apply temperature to logits and predict its effect on sampling and calibration.
  • Implement a numerically stable log-softmax and cross-entropy in NumPy.

Before this: Probability and Statistics for AI, Calculus and Gradients: How Networks Learn

Nearly every classifier and every language model is trained by minimizing one number: the cross-entropy between the data and the model's predicted distribution. Language models are compared by perplexity; distillation and RLHF use KL divergence; sampling is controlled by temperature on logits. All of these come from information theory, the mathematics of uncertainty and surprise that Claude Shannon introduced in 1948. This lesson derives them from one idea, connects them to maximum likelihood, and shows how to compute them without numerical overflow.

Intuition: surprise is measured in bits

If someone tells you the sun rose this morning, you learn almost nothing; if they tell you it snowed in Dallas in July, you learn a lot. Information is surprise, and surprise is high for unlikely events. A good predictor is one that is rarely surprised. Cross-entropy is just "the average surprise your model experiences on real data", and training lowers it.

To make this quantitative, imagine sending messages with a code. Frequent symbols should get short codewords and rare ones long codewords (Morse code gives "E" a single dot). Shannon showed that the best possible average codeword length is set by the distribution's entropy, and that using a code designed for the wrong distribution costs extra bits, exactly the KL divergence.

Self-information and entropy

The self-information (surprisal) of an outcome with probability pp is

I(x)=−log⁡p(x).I(x) = -\log p(x).

With log⁡2\log_2 it is measured in bits; with the natural log, in nats (1 nat=1/ln⁡2≈1.4431 \text{ nat} = 1/\ln 2 \approx 1.443 bits). Deep-learning frameworks use natural logs, so losses are in nats. A certain event (p=1p = 1) carries 0 information; a fair coin flip (p=1/2p = 1/2) carries 1 bit.

The entropy of a distribution pp is the expected surprisal:

H(p)=−∑xp(x)log⁡p(x)=Ex∼p[−log⁡p(x)],H(p) = -\sum_{x} p(x) \log p(x) = \mathbb{E}_{x \sim p}[-\log p(x)],

with the convention 0log⁡0=00 \log 0 = 0. For KK outcomes, 0≤H(p)≤log⁡K0 \le H(p) \le \log K; the minimum is a deterministic distribution, the maximum the uniform one.

Worked example. A fair coin: H=−2×12log⁡212=1H = -2 \times \tfrac12 \log_2 \tfrac12 = 1 bit. A biased coin with p=(0.9,0.1)p = (0.9, 0.1):

H=−(0.9log⁡20.9+0.1log⁡20.1)=−(0.9×(−0.152)+0.1×(−3.322))=0.137+0.332≈0.469 bits.H = -(0.9 \log_2 0.9 + 0.1 \log_2 0.1) = -(0.9 \times (-0.152) + 0.1 \times (-3.322)) = 0.137 + 0.332 \approx 0.469 \text{ bits}.

The biased coin is more predictable, so it has lower entropy. Where entropy appears in AI: decision trees split on information gain (reduction in entropy); reinforcement-learning algorithms add an entropy bonus to keep policies exploring; and the entropy of a model's predictive distribution is a simple uncertainty signal (high entropy over next tokens often accompanies an LLM being unsure).

Cross-entropy

If data truly come from pp but you predict with a model qq, your average surprise is the cross-entropy

H(p,q)=−∑xp(x)log⁡q(x)=Ex∼p[−log⁡q(x)].H(p, q) = -\sum_x p(x) \log q(x) = \mathbb{E}_{x \sim p}[-\log q(x)].

In classification, the "true distribution" for one example is a one-hot vector: all mass on the correct class yy. The sum then collapses to a single term:

ℓCE=−log⁡q(y).\ell_{\text{CE}} = -\log q(y).

So cross-entropy loss is simply the negative log of the probability the model assigned to the correct answer. Worked example: three classes, true class 0, prediction q=(0.7,0.2,0.1)q = (0.7, 0.2, 0.1): ℓ=−ln⁡0.7≈0.357\ell = -\ln 0.7 \approx 0.357 nats. If instead q(y)=0.01q(y) = 0.01, ℓ=−ln⁡0.01≈4.605\ell = -\ln 0.01 \approx 4.605: confident wrong answers are punished heavily, and as q(y)→0q(y) \to 0 the loss goes to infinity. Over a dataset you average: 1N∑i−log⁡q(yi∣xi)\frac{1}{N}\sum_i -\log q(y_i \mid x_i), which is exactly the negative log-likelihood from the probability lesson.

KL divergence

The Kullback–Leibler divergence measures the extra surprise from using qq when the truth is pp:

DKL(p ∥ q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p).D_{\mathrm{KL}}(p \,\|\, q) = \sum_x p(x) \log \frac{p(x)}{q(x)} = H(p, q) - H(p).

Properties: DKL(p∥q)≥0D_{\mathrm{KL}}(p\|q) \ge 0 with equality only when p=qp = q (Gibbs' inequality), and it is not symmetric, so it is not a true distance.

Worked example. p=(0.5,0.5)p = (0.5, 0.5), q=(0.9,0.1)q = (0.9, 0.1), natural logs:

DKL(p∥q)=0.5ln⁡0.50.9+0.5ln⁡0.50.1=0.5(−0.588)+0.5(1.609)≈0.511 nats,D_{\mathrm{KL}}(p\|q) = 0.5 \ln\frac{0.5}{0.9} + 0.5 \ln \frac{0.5}{0.1} = 0.5(-0.588) + 0.5(1.609) \approx 0.511 \text{ nats}, DKL(q∥p)=0.9ln⁡0.90.5+0.1ln⁡0.10.5=0.9(0.588)+0.1(−1.609)≈0.368 nats.D_{\mathrm{KL}}(q\|p) = 0.9 \ln \frac{0.9}{0.5} + 0.1 \ln \frac{0.1}{0.5} = 0.9(0.588) + 0.1(-1.609) \approx 0.368 \text{ nats}.

Because H(p)H(p) does not depend on the model, minimizing cross-entropy H(p,q)H(p, q) over qq is the same as minimizing DKL(p∥q)D_{\mathrm{KL}}(p\|q). That is the deep reason cross-entropy is the right training objective: it pulls the model distribution toward the data distribution.

Where KL appears: knowledge distillation trains a student to match a teacher's softened output distribution; RLHF and related methods penalize the KL divergence between the fine-tuned policy and the reference model so the model does not drift too far; variational autoencoders include a KL term pulling the latent distribution toward a prior. The direction matters: DKL(p∥q)D_{\mathrm{KL}}(p\|q) (forward) heavily penalizes qq for missing places where pp has mass, so it is "mass-covering"; DKL(q∥p)D_{\mathrm{KL}}(q\|p) (reverse) penalizes qq for putting mass where pp has little, so it is "mode-seeking".

Logits and softmax

Networks output unconstrained real numbers called logits z=(z1,…,zK)\mathbf{z} = (z_1, \dots, z_K). The softmax turns them into a probability distribution:

softmax(z)k=ezk∑j=1Kezj.\mathrm{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}.

Every output is positive and they sum to 1. Softmax is invariant to adding a constant to all logits (ezk+c/∑jezj+ce^{z_k + c} / \sum_j e^{z_j + c}, the ece^c cancels), so only differences between logits matter. For two classes, softmax reduces to the sigmoid of the logit difference.

Worked example. z=(2,1,0.1)\mathbf{z} = (2, 1, 0.1): e2=7.389e^{2} = 7.389, e1=2.718e^{1} = 2.718, e0.1=1.105e^{0.1} = 1.105; sum =11.213= 11.213; probabilities ≈(0.659,0.242,0.099)\approx (0.659, 0.242, 0.099).

Temperature

Dividing logits by a temperature T>0T > 0 before the softmax reshapes the distribution:

qk(T)=ezk/T∑jezj/T.q_k(T) = \frac{e^{z_k / T}}{\sum_j e^{z_j/T}}.
TTscaled logitsprobabilities
0.5(4, 2, 0.2)(0.864, 0.117, 0.019)
1(2, 1, 0.1)(0.659, 0.242, 0.099)
2(1, 0.5, 0.05)(0.502, 0.304, 0.194)

As T→0T \to 0 the distribution approaches the argmax (greedy decoding); as T→∞T \to \infty it approaches uniform. When sampling text, low temperature gives focused, repetitive output and high temperature gives diverse, error-prone output. Distillation uses T>1T > 1 on both teacher and student so the student learns from the relative probabilities of wrong classes ("dark knowledge"), as Hinton, Vinyals and Dean described in 2015. Temperature scaling is also a standard post-hoc calibration method: fit a single TT on a validation set to make probabilities honest without changing the argmax.

Softmax plus cross-entropy: the gradient

Combine softmax and cross-entropy for one example with logits z\mathbf{z} and one-hot target y\mathbf{y}:

ℓ=−log⁡ezy∑jezj=−zy+log⁡∑jezj.\ell = -\log \frac{e^{z_y}}{\sum_j e^{z_j}} = -z_y + \log \sum_j e^{z_j}.

Differentiate with respect to zkz_k: the first term gives −1-1 if k=yk = y, and the derivative of the log-sum-exp is ezk/∑jezj=qke^{z_k}/\sum_j e^{z_j} = q_k. Therefore

∂ℓ∂zk=qk−yk,∇zℓ=q−y.\frac{\partial \ell}{\partial z_k} = q_k - y_k, \qquad \nabla_{\mathbf{z}} \ell = \mathbf{q} - \mathbf{y}.

The gradient is "prediction minus target", bounded between −1-1 and 11 per logit, and it never vanishes while the model is wrong. For the example above with true class 0, ∇=(0.659−1,0.242,0.099)=(−0.341,0.242,0.099)\nabla = (0.659 - 1, 0.242, 0.099) = (-0.341, 0.242, 0.099): raise the correct logit, lower the others. Squared error on top of a softmax or sigmoid lacks this property; its gradient includes the softmax/sigmoid derivative, which goes to zero when the output saturates, so a confidently wrong model learns slowly.

Why cross-entropy for classification and MSE for regression

Both losses fall out of maximum likelihood with different noise models:

  • Classification. Model the label as categorical with probabilities q=softmax(z)\mathbf{q} = \mathrm{softmax}(\mathbf{z}). The NLL of the observed label is −log⁡qy-\log q_y: cross-entropy. (Binary case: Bernoulli likelihood gives binary cross-entropy −[ylog⁡p^+(1−y)log⁡(1−p^)]-[y \log \hat p + (1-y)\log(1 - \hat p)].)
  • Regression. Model the target as Gaussian around the prediction: y∼N(y^,σ2)y \sim \mathcal{N}(\hat y, \sigma^2). The NLL is (y−y^)22σ2+12log⁡(2πσ2)\frac{(y - \hat y)^2}{2\sigma^2} + \frac12 \log(2\pi\sigma^2); with σ\sigma fixed, minimizing it is minimizing squared error. If you assume Laplace noise instead, you get mean absolute error, which is more robust to outliers.

Choosing a loss is therefore choosing an assumption about how the data are distributed around the model's prediction.

Perplexity and language models

A language model factorizes the probability of a token sequence x1,…,xNx_1, \dots, x_N by the chain rule of probability, p(x1:N)=∏t=1Np(xt∣x<t)p(x_{1:N}) = \prod_{t=1}^N p(x_t \mid x_{<t}), and is trained to minimize the average per-token cross-entropy

ℓˉ=−1N∑t=1Nlog⁡p(xt∣x<t).\bar\ell = -\frac{1}{N}\sum_{t=1}^N \log p(x_t \mid x_{<t}).

Perplexity is its exponential:

PPL=exp⁡(ℓˉ)=(∏t=1N1p(xt∣x<t))1/N,\mathrm{PPL} = \exp(\bar\ell) = \left(\prod_{t=1}^N \frac{1}{p(x_t \mid x_{<t})}\right)^{1/N},

the geometric mean of inverse probabilities. Intuitively, a perplexity of kk means the model is, on average, as uncertain as if it were choosing uniformly among kk tokens. A uniform model over a 50,000-token vocabulary has perplexity 50,000; a perfect model has perplexity 1.

Worked example. A model assigns probabilities $0.5, 0.25, 0.125, 0.5$ to four actual tokens. Per-token losses: $0.693, 1.386, 2.079, 0.693$ nats; mean ≈1.213\approx 1.213; perplexity =e1.213≈3.36= e^{1.213} \approx 3.36. Check via the geometric mean: (2×4×8×2)1/4=1281/4≈3.36(2 \times 4 \times 8 \times 2)^{1/4} = 128^{1/4} \approx 3.36.

Caveats: perplexity depends on the tokenizer (a model with a larger vocabulary predicts fewer, harder tokens), so it is only comparable between models sharing a tokenizer and test text. For tokenizer-independent comparison people use bits per byte or bits per character. And lower perplexity does not guarantee better instruction following or reasoning; it measures fit to a text distribution.

Numerically stable log-softmax

Naively computing eze^{z} overflows float32 for zz above about 88, and taking log⁡\log of a probability that underflowed to 0 gives −∞-\infty. The fix uses the shift invariance: with m=max⁡jzjm = \max_j z_j,

log⁡softmax(z)k=zk−m−log⁡∑jezj−m.\log \mathrm{softmax}(\mathbf{z})_k = z_k - m - \log \sum_j e^{z_j - m}.

Now the largest exponent is e0=1e^0 = 1, so nothing overflows, and the sum is at least 1, so the log is safe. This is the log-sum-exp trick.

import numpy as np

def log_softmax(z, axis=-1):
    m = z.max(axis=axis, keepdims=True)
    return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True))

def cross_entropy(logits, labels):                # logits (B, K), labels (B,)
    lp = log_softmax(logits)
    return -lp[np.arange(len(labels)), labels].mean()

def entropy(p):  return -(p * np.log(np.where(p > 0, p, 1))).sum(-1)
def kl(p, q):    return (p * (np.log(p) - np.log(q))).sum(-1)

z = np.array([[2.0, 1.0, 0.1]])
for T in (0.5, 1.0, 2.0):
    print(T, np.exp(log_softmax(z / T)).round(3))

big = np.array([[1000.0, 1001.0, 1002.0]])
print(np.exp(log_softmax(big)).round(3))          # [[0.09 0.245 0.665]], no overflow

print(round(cross_entropy(z, np.array([0])), 4))  # 0.417 = -log 0.659
print(kl(np.array([.5, .5]), np.array([.9, .1])).round(3),
      kl(np.array([.9, .1]), np.array([.5, .5])).round(3))   # 0.511 0.368

# gradient of CE wrt logits equals softmax - onehot (numerical check)
q = np.exp(log_softmax(z))[0]; y = np.array([1., 0., 0.])
eps = 1e-6; num = np.zeros(3)
for k in range(3):
    zp, zm = z.copy(), z.copy(); zp[0, k] += eps; zm[0, k] -= eps
    num[k] = (cross_entropy(zp, np.array([0])) - cross_entropy(zm, np.array([0]))) / (2 * eps)
print(num.round(4), (q - y).round(4))

probs = np.array([0.5, 0.25, 0.125, 0.5])
print("perplexity", round(np.exp(-np.log(probs).mean()), 3))   # 3.364

Note the loss on the logits (2,1,0.1)(2, 1, 0.1) is −ln⁡0.659≈0.417-\ln 0.659 \approx 0.417; the earlier 0.3570.357 example used the probability 0.70.7 directly. Frameworks fuse softmax and log for exactly this stability reason: PyTorch's nn.CrossEntropyLoss and F.cross_entropy take raw logits and apply a stable log-softmax internally, and F.log_softmax exists for when you need log-probabilities.

Common pitfalls

  • Applying softmax before a loss that expects logits. Passing probabilities into CrossEntropyLoss applies softmax twice; the model still trains, but poorly.
  • Computing log(softmax(x)) in two steps. Use a fused log-softmax or cross-entropy to avoid -inf and nan.
  • Comparing perplexities across tokenizers or datasets. The numbers are not on the same scale.
  • Mixing bits and nats. Framework losses are in nats; divide by ln⁡2\ln 2 for bits.
  • KL direction errors. DKL(p∥q)D_{\mathrm{KL}}(p\|q) and DKL(q∥p)D_{\mathrm{KL}}(q\|p) give different gradients and behaviours; check which one a method specifies, and note that torch.nn.functional.kl_div expects its first argument as log-probabilities of the model.
  • Taking log(0). Add label smoothing, clip probabilities, or work in log space.

In practice

  • Train classifiers on logits with fused cross-entropy; use label smoothing (mixing the one-hot target with a little uniform mass) when overconfidence is a problem.
  • Report validation loss in nats per token and perplexity for language models, and also bits per byte when comparing different tokenizers.
  • Calibrate with a single temperature fitted on held-out data when probabilities drive decisions.
  • Tune sampling temperature per task: low values (or greedy decoding) for extraction and code, moderate values for open-ended writing.
  • Watch the KL to the reference model during preference fine-tuning; a rapidly growing KL often signals reward hacking.

Key takeaways

  • Entropy is the expected surprise of a distribution; cross-entropy is the expected surprise when predicting with a model.
  • Minimizing cross-entropy equals minimizing KL divergence from data to model and equals maximum likelihood.
  • The gradient of softmax cross-entropy with respect to the logits is simply predicted probabilities minus the one-hot target.
  • Cross-entropy follows from a categorical likelihood and MSE from a Gaussian likelihood; the loss encodes a noise assumption.
  • Perplexity is the exponential of mean per-token cross-entropy and is only comparable across models with the same tokenizer and data.
  • Always compute log-probabilities with the log-sum-exp trick or a fused library function.

Terms in this lesson

Self-information
The surprise of an outcome, equal to the negative logarithm of its probability.
Entropy
The expected self-information of a distribution, measuring its uncertainty.
Cross-entropy
The expected negative log-probability that a model q assigns to outcomes drawn from the true distribution p.
KL divergence
A non-negative, asymmetric measure of how much a distribution q differs from p, equal to cross-entropy minus entropy.
Logits
The unnormalized real-valued scores a model outputs before a softmax or sigmoid converts them to probabilities.
Softmax
The function that exponentiates logits and normalizes them to sum to one, producing a categorical distribution.
Temperature
A positive scalar that divides logits before softmax, sharpening the distribution when below 1 and flattening it when above 1.
Perplexity
The exponential of the average per-token negative log-likelihood, interpretable as an effective number of equally likely choices.
Log-sum-exp trick
Subtracting the maximum logit before exponentiating so that log-softmax and related quantities can be computed without overflow.

Check your understanding

  1. 1.

    A model assigns probability 0.25 to the correct class. What is the cross-entropy loss for that example in bits?

  2. 2.

    Logits (3, 1, 0) with true class 1. What is the gradient of the softmax cross-entropy with respect to the logits, to two decimals?

  3. 3.

    Two language models report perplexities of 8.1 and 9.4 on different test sets with different tokenizers. What can you conclude?

  4. 4.

    You need to predict house prices and believe errors are roughly Gaussian with constant variance. Which loss follows from maximum likelihood?

  5. 5.

    What happens to the softmax distribution as temperature T approaches 0?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    Compute the entropy in bits of the distribution p=(0.5,0.25,0.125,0.125)p = (0.5, 0.25, 0.125, 0.125). Then compute the cross-entropy H(p,q)H(p, q) in bits when the model is uniform, q=(0.25,0.25,0.25,0.25)q = (0.25, 0.25, 0.25, 0.25), and the KL divergence DKL(p∥q)D_{\mathrm{KL}}(p\|q).

    Show solution

    H(p)=0.5⋅1+0.25⋅2+0.125⋅3+0.125⋅3=0.5+0.5+0.375+0.375=1.75H(p) = 0.5\cdot1 + 0.25\cdot2 + 0.125\cdot3 + 0.125\cdot3 = 0.5 + 0.5 + 0.375 + 0.375 = 1.75 bits.

    H(p,q)=−∑p(x)log⁡20.25=2∑p(x)=2H(p, q) = -\sum p(x)\log_2 0.25 = 2 \sum p(x) = 2 bits.

    DKL(p∥q)=H(p,q)−H(p)=2−1.75=0.25D_{\mathrm{KL}}(p\|q) = H(p, q) - H(p) = 2 - 1.75 = 0.25 bits. Interpretation: a code optimized for the uniform model wastes a quarter bit per symbol on data from pp.

  2. Exercise 2Core

    A language model is evaluated on a 1,000-token text and its summed negative log-likelihood is 2,300 nats. (a) What is the mean loss per token in nats and in bits? (b) What is the perplexity? (c) If a change lowers the mean loss by 0.1 nats per token, what is the new perplexity?

    Show solution

    (a) 2300/1000=2.32300/1000 = 2.3 nats per token; in bits 2.3/ln⁡2≈3.3182.3/\ln 2 \approx 3.318 bits.

    (b) PPL=e2.3≈9.97\mathrm{PPL} = e^{2.3} \approx 9.97.

    (c) e2.2≈9.03e^{2.2} \approx 9.03. A 0.1-nat drop always multiplies perplexity by e−0.1≈0.905e^{-0.1} \approx 0.905, a 9.5% reduction.

  3. Exercise 3Core

    Show that softmax(z+c1)=softmax(z)\mathrm{softmax}(\mathbf z + c\mathbf 1) = \mathrm{softmax}(\mathbf z) for any constant cc, and use this to explain why log⁡softmax\log\mathrm{softmax} computed with the max-subtraction trick is exact rather than an approximation.

    Show solution

    softmax(z+c)k=ezk+c∑jezj+c=ecezkec∑jezj=softmax(z)k\mathrm{softmax}(\mathbf z + c)_k = \frac{e^{z_k + c}}{\sum_j e^{z_j + c}} = \frac{e^c e^{z_k}}{e^c \sum_j e^{z_j}} = \mathrm{softmax}(\mathbf z)_k.

    Choosing c=−mc = -m with m=max⁡jzjm = \max_j z_j therefore leaves the result mathematically unchanged; it only changes which intermediate numbers are computed. Taking logs, log⁡softmax(z)k=(zk−m)−log⁡∑jezj−m\log\mathrm{softmax}(\mathbf z)_k = (z_k - m) - \log\sum_j e^{z_j - m} is an algebraic identity. The exponents are all ≤0\le 0, so no overflow occurs, and the sum includes e0=1e^0 = 1, so the logarithm never sees 0.

  4. Exercise 4Challenge

    Implement knowledge-distillation loss in NumPy: given teacher logits and student logits of shape (B,K)(B, K) and temperature TT, compute the mean over the batch of T2⋅DKL(pT∥qT)T^2 \cdot D_{\mathrm{KL}}(p_T \| q_T) where pTp_T and qTq_T are the teacher's and student's temperature-softened softmax distributions. Use stable log-softmax. Test with teacher (5,2,0)(5, 2, 0) and student (3,2,1)(3, 2, 1) at T=1T = 1 and T=4T = 4. Explain why the T2T^2 factor is used.

    Show solution
    import numpy as np
    
    def log_softmax(z, axis=-1):
        m = z.max(axis=axis, keepdims=True)
        return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True))
    
    def distill_loss(teacher, student, T):
        lp = log_softmax(teacher / T)        # teacher log-probs
        lq = log_softmax(student / T)        # student log-probs
        kl = (np.exp(lp) * (lp - lq)).sum(axis=-1)
        return (T ** 2) * kl.mean()
    
    t = np.array([[5.0, 2.0, 0.0]])
    s = np.array([[3.0, 2.0, 1.0]])
    for T in (1.0, 4.0):
        print(T, round(distill_loss(t, s, T), 4))
    

    Output: 1.0 0.2392 and 4.0 0.7715. At T=1T = 1 the teacher is about (0.946,0.047,0.006)(0.946, 0.047, 0.006) and the student (0.665,0.245,0.090)(0.665, 0.245, 0.090), giving a KL of about 0.239 nats. At T=4T = 4 both distributions are flatter, teacher (0.569,0.269,0.163)(0.569, 0.269, 0.163) and student (0.419,0.326,0.254)(0.419, 0.326, 0.254), so the raw KL is smaller (about 0.048 nats), but multiplied by T2=16T^2 = 16 it becomes about 0.77. The softened view exposes the information in the small logits (how the teacher ranks the wrong classes), which the student currently gets wrong.

    Why T2T^2: the gradient of the softened cross-entropy with respect to the student logits is (qT−pT)/T(q_T - p_T)/T, and for large TT the difference qT−pTq_T - p_T itself shrinks roughly like 1/T1/T, so gradients scale like 1/T21/T^2. Multiplying by T2T^2 keeps the distillation term's gradient magnitude roughly constant as you change TT, so it stays balanced against the ordinary hard-label loss. This scaling is the one recommended by Hinton, Vinyals and Dean (2015).

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026