Inferensys

Glossary

Temperature Scaling

Temperature scaling is a hyperparameter technique in knowledge distillation that softens a teacher model's output probability distribution, making its 'dark knowledge' more accessible for a student model to learn.
Knowledge engineer constructing knowledge base on laptop, document hierarchy visible, casual office setup.
KNOWLEDGE DISTILLATION

What is Temperature Scaling?

Temperature scaling is a core technique in knowledge distillation that modifies the softmax function to soften a teacher model's output probabilities, facilitating the transfer of 'dark knowledge' to a student model.

Temperature scaling is a technique in knowledge distillation where a temperature parameter (T) is applied to the softmax function of a teacher model's output logits. This parameter controls the smoothness of the resulting probability distribution: a T > 1 produces a 'softer' distribution, where probabilities for incorrect classes are elevated, revealing the teacher's learned inter-class relationships. This softened output, containing dark knowledge, provides a richer training signal than hard one-hot labels, making it easier for a smaller student model to learn generalized representations.

The primary objective is to improve the student model's generalization by learning from the teacher's relative confidence across all classes, not just the top prediction. The temperature is applied identically during student training, and the standard Kullback-Leibler divergence loss is used to minimize the difference between the teacher's and student's softened outputs. Crucially, at inference, the temperature is set back to 1 (T=1) for the student model, restoring a standard, sharp probability distribution for final predictions while retaining the benefits of the softened training process.

KNOWLEDGE DISTILLATION

Key Characteristics of Temperature Scaling

Temperature scaling is a post-processing calibration technique that applies a single scalar parameter (T) to the logits of a neural network to adjust the confidence of its predicted probability distribution. It is most famously used in knowledge distillation to soften the teacher model's outputs, transferring 'dark knowledge' to a student model.

01

The Temperature Parameter (T)

The temperature (T) is a single, positive scalar hyperparameter applied to the logits before the softmax function. It directly controls the 'softness' of the output probability distribution.

  • T = 1: The standard softmax function. No change to the original model output.
  • T > 1: The distribution is softened. Probabilities become more uniform, revealing the model's relative confidence across classes (the 'dark knowledge').
  • T < 1: The distribution is sharpened, making the model more confident (peaky). This can exaggerate overconfidence and is rarely used in distillation.

The modified softmax is: softmax(z_i / T), where z are the logits.

02

Role in Knowledge Distillation

In knowledge distillation, a high temperature (e.g., T=3 to T=10) is applied to the teacher model's logits to create soft targets. These softened probabilities provide a richer training signal than hard one-hot labels.

  • The student model is trained to match these soft targets using a loss function like Kullback-Leibler (KL) Divergence.
  • The softened probabilities encode inter-class similarities. For example, an image of a '7' might have a non-zero probability for '1', teaching the student about shared features.
  • During final inference, the student uses a temperature of T=1, recovering a standard, sharp probability distribution.
03

As a Calibration Tool

Separate from distillation, temperature scaling is a highly effective post-hoc calibration method. A poorly calibrated model's predicted confidence does not match its true accuracy (e.g., predicting 0.9 confidence but being right only 70% of the time).

  • After training, a validation set is used to optimize the temperature parameter T to minimize the gap between confidence and accuracy.
  • It is a monotonic transformation that does not change the model's predicted class ranking (argmax), only the confidence scores.
  • It is computationally cheap, requiring optimization of just one parameter, and often outperforms more complex calibration methods.
04

Mathematical Foundation

The core operation is a simple scaling of the logit vector z before applying the softmax function.

Softmax with Temperature: σ(z, T)_i = exp(z_i / T) / Σ_j exp(z_j / T)

Key Properties:

  • As T → ∞, the output distribution approaches uniform (1/K for K classes).
  • As T → 0, the output approaches a one-hot distribution at the highest logit.
  • The gradients passed to the student during distillation are scaled by 1/T^2, providing a more stable and gentle learning signal when T > 1.
05

Implementation & Practical Use

Implementing temperature scaling is straightforward in modern deep learning frameworks.

For Distillation:

  1. Forward pass teacher batch with high T to get soft targets.
  2. Forward pass student batch with the same high T.
  3. Compute KL divergence loss between the two softened distributions.
  4. Combine with a standard cross-entropy loss using hard labels (often with a weighting factor α).

For Calibration:

  1. Train model as normal.
  2. On a held-out validation set, optimize T to minimize Negative Log Likelihood (NLL) or Expected Calibration Error (ECE).
  3. Apply the optimized T to scale logits during all future inference.
06

Limitations and Considerations

While powerful, temperature scaling has specific constraints.

  • Single-Parameter Simplicity: Its strength is also a limitation. It cannot correct calibration errors that require non-monotonic adjustments across different parts of the input space.
  • Dataset Dependency: The optimal T for distillation or calibration is dataset and model-dependent and must be validated.
  • Logits Requirement: It requires access to the model's logits, not just the final class prediction. Some APIs may not expose these.
  • No Architectural Change: It does not modify the model's weights or architecture; it is a inference-time adjustment. For complex miscalibration, methods like Platt scaling or isotonic regression may be more flexible.
KNOWLEDGE DISTILLATION

Temperature Scaling vs. Standard Training

A comparison of the core mechanisms and outcomes when training a student model using temperature-scaled soft targets from a teacher versus training directly on hard labels.

Feature / MetricStandard Training (Hard Labels)Temperature-Scaled Distillation (Soft Targets)

Primary Objective

Minimize error vs. ground-truth one-hot labels

Minimize divergence from teacher's softened probability distribution

Label Representation

Hard, one-hot vector (e.g., [0, 0, 1, 0])

Soft, probabilistic vector (e.g., [0.01, 0.04, 0.9, 0.05])

Information Transferred

Only the final, correct class

Inter-class relationships and similarity scores ("dark knowledge")

Key Hyperparameter

Learning rate, batch size

Temperature (T), distillation loss weight (α)

Typical Loss Function

Cross-Entropy Loss

Weighted sum: α * KL Divergence(T) + (1-α) * Cross-Entropy

Model Calibration

Often overconfident, poorly calibrated

Produces better calibrated, less overconfident predictions

Generalization Benefit

Standard generalization from training data

Often improved generalization and robustness via regularization effect

Primary Use Case

Training a model from scratch on a labeled dataset

Compressing a large teacher model into a smaller, efficient student model

PRACTICAL IMPLEMENTATIONS

Examples and Applications

Temperature scaling is a versatile technique primarily used to soften probability distributions for knowledge distillation, but its applications extend to model calibration and controlled text generation.

01

Core Role in Knowledge Distillation

Temperature scaling's primary application is in the teacher-student framework. By applying a temperature T > 1 to the teacher's softmax, the output distribution is softened, revealing dark knowledge—the relative similarities between incorrect classes. This richer signal, compared to hard one-hot labels, provides a more informative training target for the student model. For example, in image classification, a softened output for a 'cat' image might show high probability for 'cat', moderate for 'lynx', and low for 'truck', teaching the student about semantic relationships within the data.

02

Model Calibration for Reliable Probabilities

A critical secondary use is post-hoc calibration of neural networks. Modern models, especially large ones, are often miscalibrated—their predicted confidence scores do not match their true likelihood of being correct (e.g., predicting 0.9 confidence but being right only 70% of the time). Temperature scaling is applied as a single-parameter transformation on the logits of a trained, frozen model on a validation set. An optimal T is found to minimize the gap between confidence and accuracy, improving metrics like Expected Calibration Error (ECE). This is essential for high-stakes applications like medical diagnosis or autonomous driving, where confidence scores must be trustworthy.

03

Controlling Creativity in Text Generation

In large language model inference, temperature scaling directly controls the randomness or creativity of generated text. It is applied to the logits before sampling the next token.

  • Low Temperature (T < 1): Sharpens the distribution, making high-probability tokens more likely. Output becomes more deterministic, focused, and repetitive.
  • High Temperature (T > 1): Flattens the distribution, giving lower-probability tokens a better chance. Output becomes more diverse, creative, and potentially nonsensical. For example, code generation typically uses a low T (~0.2) for deterministic, correct syntax, while creative writing might use a higher T (~0.8-1.2). This parameter is a key lever in prompt engineering for steering model behavior.
04

Integration with Advanced Distillation Variants

Temperature scaling is a foundational component enabling more sophisticated distillation techniques:

  • Online Distillation: Used in frameworks like Deep Mutual Learning, where peer models teach each other using softened targets generated in real-time during co-training.
  • Self-Distillation: In architectures like Born-Again Networks, a model distills knowledge from its own earlier training iterations, relying on temperature-scaled outputs from its previous checkpoint as soft labels.
  • Data-Free Distillation: When the original training data is unavailable, temperature-scaled outputs from the teacher can help generate or guide the creation of synthetic data for student training.
  • Quantization-Aware Distillation (QAT): Temperature-scaled soft targets can be used while simulating quantization noise, helping the student learn a robust, efficient representation from the start.
05

Vision Transformer Distillation (DeiT)

A landmark application is in Data-efficient Image Transformers (DeiT). DeiT introduced a distillation token—a learnable vector that attends to the teacher model's temperature-scaled class predictions throughout the transformer layers. The student model (DeiT) is trained with a combined loss: a standard cross-entropy loss with true labels and a distillation loss (e.g., KL divergence) against the softened outputs of a ConvNet teacher (like RegNet). This use of temperature scaling was pivotal in training competitive vision transformers without the massive, private datasets used to train the original ViT models.

06

Contrastive and Relational Distillation

Temperature scaling appears in advanced loss functions beyond standard KL divergence. In contrastive distillation, the InfoNCE loss commonly uses a temperature parameter τ to scale the similarity scores between positive and negative sample pairs in the representation space. This controls how concentrated the distribution is over similar examples. Similarly, in relational knowledge distillation, where the student learns to mimic relationships between data sample pairs as modeled by the teacher, temperature can soften the relationship distributions, making the relative similarities easier to learn. This demonstrates the parameter's utility in transferring structural, rather than just pointwise, knowledge.

TEMPERATURE SCALING

Frequently Asked Questions

Temperature scaling is a core technique in knowledge distillation used to soften a teacher model's output probabilities, making its 'dark knowledge' more accessible for a student model to learn.

Temperature scaling is a hyperparameter technique applied to the softmax function in a neural network's final layer to control the 'softness' of its output probability distribution. By introducing a temperature parameter (T), it adjusts how confident or uncertain the model appears in its predictions. A higher temperature (T > 1) produces a softer, more uniform probability distribution across classes, while a lower temperature (T < 1) sharpens the distribution, making the highest probability more dominant. Its primary application is in knowledge distillation, where a softened distribution from a teacher model provides richer training signal than hard labels.

Mathematically, the temperature-scaled softmax for class i is computed as:

python
softmax(z_i, T) = exp(z_i / T) / sum_j(exp(z_j / T))

where z are the raw output logits. When T = 1, it's the standard softmax.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.