Knowledge Distillation › Temperature in Distillation

Michael BrenndoerferFebruary 24, 20269 min read
Language AI HandbookAll chapters
Part 41 of 67Model Compression
Chapter 307Knowledge Distillation › Temperature in Distillation
Reading section 3 of 10 · Temperature in Distillation · 9 minSection 3 of 10 · 9 min

Book contents

Section 3 of 10 · 9 min read

Knowledge Distillation › Temperature in DistillationOne section · Sections in this chapter3 / 10 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The most practically important concept in distillation is temperature scaling, and it is worth understanding in detail because it fundamentally changes what information the student receives. Without temperature scaling, distillation often provides little improvement over hard-label training, because the soft labels are too similar to hard labels to provide additional signal.

The Problem with Sharp Distributions

Language model outputs tend to be sharply peaked. Given a sentence like "The sky is ___", the model assigns very high probability to "blue" and near-zero probability to essentially everything else. When these near-zero probabilities are used as soft labels, they provide almost no additional information compared to hard labels: the distribution is essentially one-hot.

The teacher's knowledge about relationships between less likely tokens is compressed into these tiny probability values. Words that are semantically related to "blue" (like "clear," "gray," or "overcast") receive probabilities that are only slightly higher than completely unrelated words. At floating-point precision, these differences exist, but they are numerically tiny. A student trying to match these near-zero values receives a training signal that is essentially the same as trying to match zeros. The relational structure is there in principle, but it is buried beneath the noise floor of floating-point arithmetic.

This is the fundamental problem that temperature scaling solves. The information is present in the teacher's logits, but it is compressed in a way that makes it invisible to the training objective. We need to uncompress it.

Softmax Temperature

Temperature scaling addresses this by flattening the distribution before using it as a soft label. The teacher's logits ziTz^T_i are divided by a temperature parameter τ\tau before the softmax is applied:

piT(τ)=exp⁡(ziT/τ)∑j=1Vexp⁡(zjT/τ)p^T_i(\tau) = \frac{\exp(z^T_i / \tau)}{\sum_{j=1}^{V} \exp(z^T_j / \tau)}

where:

  • ziTz^T_i: the teacher's logit (pre-softmax score) for token ii
  • τ\tau: the temperature parameter (τ>0\tau > 0)
  • piT(τ)p^T_i(\tau): the temperature-scaled probability for token ii

When τ=1\tau = 1, this is the standard softmax. When τ>1\tau > 1, the distribution becomes flatter: smaller probabilities grow relative to the largest ones. When τ<1\tau < 1, the distribution becomes sharper, concentrating even more mass on the peak.

To see why temperature matters concretely, consider logits [10,2,1,0][10, 2, 1, 0]. At τ=1\tau = 1, the softmax gives approximately [0.9997,0.0003,0.0001,0.00004][0.9997, 0.0003, 0.0001, 0.00004]: essentially a one-hot distribution. At τ=4\tau = 4, the same logits give roughly [0.76,0.13,0.08,0.05][0.76, 0.13, 0.08, 0.05]: a much softer distribution where the relative magnitudes of all four logits are visible in the probability values. The smaller logits now carry meaningful probability mass and can guide the student's learning.

The mechanics of why this works come from the exponential function. When logits are divided by a large τ\tau, the differences between them shrink. The exponential function maps small differences to values close to 1, so the ratio between the largest and smallest probabilities decreases. What was a thousand-fold difference at τ=1\tau = 1 becomes a moderate difference at τ=4\tau = 4, moving probabilities that were numerically invisible into ranges where the gradient signal is strong.

During distillation, the same temperature τ\tau is applied to both the teacher's distribution (to produce soft labels) and the student's distribution (to compute the loss). The student is trained to match the teacher's soft output. After training is complete, the temperature is reset to τ=1\tau = 1 for inference. The student's weights have been shaped by exposure to the temperature-scaled distributions, but it produces predictions at the standard temperature.

Why Temperature Amplifies Dark Knowledge

Hinton et al. introduced the term "dark knowledge" to describe the information encoded in the small probabilities that standard training ignores. A teacher that assigns probability 0.0001 to "feline" when predicting the word "cat" is revealing a structural relationship between these two words. This relationship is invisible under hard-label training but becomes visible when the distribution is temperature-scaled.

The key insight is that the ratio of probabilities at high temperature reveals structure that absolute probabilities hide. If the teacher assigns logit 10 to "cat," logit 2 to "feline," and logit −5-5 to "airplane," the ratio p(feline)/p(airplane)p(\text{feline}) / p(\text{airplane}) encodes the semantic proximity of cat and feline relative to airplane. At low temperature, both probabilities round toward zero and the ratio becomes numerically unreliable. At high temperature, both probabilities are substantial and the ratio is preserved, giving the student a meaningful gradient signal that "feline" and "cat" are semantically related while "airplane" is not.

This is the distinction between distillation and a minor regularization variant. The teacher's logits contain a rich relational structure built up over training. Temperature scaling is the tool that makes this structure accessible to the student.

In[3]:
Code
import numpy as np


def softmax_with_temperature(logits, temperature):
    logits = np.array(logits, dtype=float)
    scaled = logits / temperature
    # Numerical stability: subtract max before exp
    scaled -= scaled.max()
    exp_vals = np.exp(scaled)
    return exp_vals / exp_vals.sum()


# Teacher logits for a 5-token vocabulary: "cat", "feline", "dog", "table", "airplane"
teacher_logits = np.array([8.0, 5.0, 4.5, 1.0, -2.0])
tokens = ["cat", "feline", "dog", "table", "airplane"]
temperatures = [1, 2, 4, 8]

probs_by_temp = {
    tau: softmax_with_temperature(teacher_logits, tau) for tau in temperatures
}
Out[4]:
Console
Temperature effect on teacher distribution
Token         tau=1      tau=2      tau=4      tau=8    
----------------------------------------------------
cat           0.92512  0.69743  0.46618  0.32935
feline        0.04606  0.15562  0.22021  0.22636
dog           0.02794  0.12119  0.19433  0.21264
table         0.00084  0.02106  0.08101  0.13729
airplane      0.00004  0.00470  0.03827  0.09436

As temperature increases, the near-zero probabilities for "feline," "dog," and even "table" become large enough to compare. At τ=8\tau = 8, all five tokens carry substantial probability mass and the student can distinguish between them based on their relative values. The teacher's implicit semantic ranking, from closely related ("feline," "dog") to moderately related ("table") to unrelated ("airplane"), becomes visible in the training signal.

Out[5]:
Visualization
Bar chart showing a near-one-hot distribution over 5 tokens at temperature 1.
Teacher distribution at temperature 1, nearly identical to a hard label. Almost all probability mass sits on 'cat', leaving negligible signal in the remaining four tokens. A student trained on this distribution learns little about the relative relationships between outputs.
Bar chart showing a soft probability distribution over 5 tokens at temperature 4.
Teacher distribution at temperature 4. The distribution is significantly softer, allowing the student to see the relative ranking of all five tokens. The teacher's implicit semantic structure, where 'feline' and 'dog' are much more probable than 'airplane', becomes a learnable training signal.

Choosing the Temperature

The right temperature depends on how peaked the teacher's distribution is and how much dark knowledge you want to expose. For tasks with very confident outputs (like clearly labeled image classification), moderate temperatures of τ=2\tau = 2 to τ=4\tau = 4 are usually sufficient to make the secondary probabilities visible. For tasks with ambiguous targets (like next-token prediction in language models), higher temperatures up to τ=10\tau = 10 can reveal richer structure, but there is a point of diminishing returns.

At very high temperatures, the distribution approaches a uniform distribution, and the distinctions between tokens blur. The teacher's guidance becomes noise rather than signal. At very low temperatures, the distribution collapses toward a one-hot vector and the soft labels carry no more information than hard labels. The sweet spot is in between: high enough that secondary probabilities are substantial, low enough that the teacher's ranking of outputs is still preserved.

A practical approach is to treat the temperature as a hyperparameter and tune it on a held-out validation set. In practice, values in the range [2,8][2, 8] work well for most classification and language modeling tasks. For well-trained, high-confidence teachers, lean toward lower temperatures; for less confident or more uncertain teachers, lean toward higher temperatures.

Rescaling the Loss

When using temperature scaling during distillation, the gradients of the distillation loss are scaled by 1/τ21/\tau^2 compared to the gradients of the standard supervised loss. This happens because the softmax function with temperature τ\tau produces logit gradients that are 1/τ1/\tau times smaller than those of the standard softmax, and this factor appears twice in the computation: once for the teacher's distribution and once for the student's. The net effect is that increasing τ\tau reduces the magnitude of the distillation gradient by a factor of τ2\tau^2.

To keep the distillation loss contribution stable relative to the supervised loss when varying τ\tau, Hinton et al. recommend multiplying the distillation loss term by τ2\tau^2:

L=α⋅τ2⋅Ldistill(τ)+(1−α)⋅LCE\mathcal{L} = \alpha \cdot \tau^2 \cdot \mathcal{L}_{\text{distill}}(\tau) + (1 - \alpha) \cdot \mathcal{L}_{\text{CE}}

where Ldistill(τ)\mathcal{L}_{\text{distill}}(\tau) denotes the distillation loss computed with temperature τ\tau. The τ2\tau^2 factor compensates for the gradient shrinkage caused by the temperature scaling, making sure that the magnitude of the distillation gradient remains roughly constant as τ\tau varies. This makes it easier to tune α\alpha independently of τ\tau: you can increase the temperature to reveal more dark knowledge without accidentally reducing the effective learning rate on the distillation objective.

This τ2\tau^2 correction is often omitted in implementations without dramatic consequences, especially when α\alpha is tuned empirically, but it simplifies hyperparameter tuning and is good practice when sweeping over temperature values.