Inferensys

Glossary

Temperature Scaling

Temperature scaling is a hyperparameter technique in knowledge distillation that softens a neural network's output probability distribution by dividing logits by a temperature (T) before the softmax, revealing richer 'dark knowledge' for training student models.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
KNOWLEDGE DISTILLATION TECHNIQUE

What is Temperature Scaling?

Temperature scaling is a core technique in knowledge distillation used to soften a neural network's output probability distribution, making its learned 'dark knowledge' more accessible for training a smaller student model.

Temperature scaling is a hyperparameter technique applied to the softmax function during knowledge distillation. It introduces a temperature parameter (T) that scales the logits (pre-softmax activations) of a teacher model before normalization. A temperature greater than 1 produces a 'softer' probability distribution over classes, where the relative differences between non-target class probabilities are amplified. This softened output, known as a soft target, provides a richer training signal than a one-hot label by revealing the teacher's internal class similarities and confidences.

The primary purpose of temperature scaling is to transfer dark knowledge—the nuanced relationships between classes learned by the teacher—to the student model. The student is trained using a loss function like Kullback-Leibler divergence to match these softened distributions. This process is fundamental to the teacher-student framework, enabling effective model compression and capability transfer. In continual learning, a variant called distillation for forgetting uses a model's own temperature-scaled outputs on past tasks as soft targets to mitigate catastrophic forgetting when learning new data.

KNOWLEDGE DISTILLATION TECHNIQUE

Key Characteristics of Temperature Scaling

Temperature scaling is a post-processing and training technique that applies a temperature parameter (T) to the softmax function to control the sharpness of a neural network's output probability distribution.

01

The Temperature Parameter (T)

The temperature parameter (T) is a scalar value that divides the logits (pre-softmax activations) before applying the softmax function: softmax(logits / T). It directly controls the entropy of the output distribution.

  • T = 1: Standard softmax, producing the model's native confidence distribution.
  • T > 1: 'Softens' the distribution, increasing entropy. Probabilities become more uniform, revealing the model's relative confidence across classes—the so-called dark knowledge.
  • T < 1: 'Hardens' the distribution, making the winning class's probability approach 1.0. This is used for inference-time confidence calibration or creating sharper targets.
02

Softening for Knowledge Distillation

The primary role of temperature scaling is to generate soft targets for knowledge distillation. A high temperature (e.g., T=3 to T=10) is applied to the teacher model's logits.

Key Mechanism:

  • The softened probabilities preserve the teacher's knowledge of inter-class relationships. For example, an image of a 'cat' might have a high probability for 'cat', a moderate probability for 'lynx', and a near-zero probability for 'car'. This richer signal teaches the student model more than a one-hot 'cat' label.
  • The student is trained using a loss function (like KL Divergence Loss) to match this softened distribution, often while also learning from the true hard labels.
03

Confidence Calibration

Temperature scaling is a state-of-the-art method for post-hoc calibration of neural networks. A model is calibrated when its predicted confidence (e.g., softmax probability of 0.9) matches its actual accuracy (e.g., is correct 90% of the time).

Process:

  1. After training, a separate validation set is used to find a single scalar temperature T.
  2. This T (often < 1) is applied to the model's logits at inference time.
  3. It adjusts the output probabilities to better reflect true likelihoods without changing the model's predicted class ranking (argmax).
  • This is critical for risk-sensitive applications like medical diagnosis or autonomous driving.
04

Mathematical Foundation

The operation is defined by a simple modification to the standard softmax:

softmax(z_i, T) = exp(z_i / T) / Σ_j exp(z_j / T)

Where z are the logits and T is the temperature.

Derivative & Gradient Effect: During distillation training, the gradient passed to the student with respect to its logits s_i is: ∂L_KL / ∂s_i = (1/T^2) * (q_i - p_i) where q is the student's softened distribution and p is the teacher's softened distribution.

  • The 1/T^2 factor acts as a gradient scaling term. Higher temperatures produce smaller gradients, effectively smoothing the loss landscape and stabilizing training.
05

Connection to Continual Learning

Temperature scaling is a key component in distillation-based continual learning algorithms like Learning without Forgetting (LwF).

Application:

  • When learning a new task, the model's predictions on new data for old tasks are recorded using a high temperature to create soft targets.
  • These soft targets are then used as a regularization loss when training on the new task, penalizing the model for deviating from its previous knowledge.
  • This technique helps mitigate catastrophic forgetting by preserving the 'dark knowledge' of how previous classes relate to each other, not just their hard labels.
06

Practical Implementation Notes

Typical Workflows:

  • For Distillation: Use a high T (e.g., 3-10) on the teacher. Train the student with a weighted sum of distillation loss (KL Divergence at temperature T) and standard cross-entropy loss (at T=1).
  • For Calibration: Train model normally. On a held-out validation set, optimize T > 0 to minimize Negative Log Likelihood (NLL) or Expected Calibration Error (ECE). Apply this T at test time.

Considerations:

  • Temperature is a hyperparameter and must be tuned for the specific model and dataset.
  • It does not change the model's architecture or the ranking of its predictions.
  • The technique is computationally inexpensive, adding negligible overhead.
KNOWLEDGE DISTILLATION TECHNIQUE

How Temperature Scaling Works: A Technical Breakdown

Temperature scaling is a core technique in knowledge distillation that modifies the output probability distribution of a neural network to facilitate the transfer of 'dark knowledge' from a teacher model to a student model.

Temperature scaling applies a single scalar parameter, T (temperature), to the logits (pre-softmax activations) of a teacher model before the softmax function. When T=1, the standard softmax is recovered. When T > 1, the resulting probability distribution is 'softened,' reducing the confidence gap between the top prediction and other classes. This softened distribution, called soft targets, reveals the teacher's relative class similarities—its 'dark knowledge'—which is a richer training signal for the student than hard one-hot labels.

The student model is then trained using a loss function, typically Kullback-Leibler (KL) divergence, to match its own temperature-scaled outputs to the teacher's soft targets. This process teaches the student not just the correct answer, but the teacher's nuanced understanding of inter-class relationships. In continual learning, temperature-scaled outputs from a model's previous state can be used as soft targets to regularize new learning, directly combating catastrophic forgetting by preserving prior knowledge.

TEMPERATURE SCALING

Primary Use Cases and Applications

Temperature scaling is a post-hoc calibration and knowledge transfer technique. Its primary applications focus on improving model reliability and enabling efficient knowledge distillation.

01

Model Calibration

Temperature scaling is a post-hoc calibration method applied after a model is trained. It adjusts the confidence of a model's predictions to better match its actual accuracy. A well-calibrated model that predicts a class with 80% probability should be correct 80% of the time. By tuning a single temperature parameter (T) on a validation set, it softens or sharpens the output distribution, reducing overconfidence without changing the model's predicted ranking of classes. This is critical for risk-sensitive applications like medical diagnosis or autonomous driving, where confidence scores must be meaningful.

T > 1
Soften distribution (calibrate)
T = 1
Original softmax
T < 1
Sharpen distribution
02

Knowledge Distillation

This is the technique's namesake and most common application. Here, temperature scaling is applied to the teacher model's logits before the student model is trained. A temperature (T > 1) is used to create soft targets—a richer, smoother probability distribution that reveals the dark knowledge of class relationships learned by the teacher. For example, an image of a 'husky' might have high probability for 'dog' and a non-zero probability for 'wolf,' which is more informative than a one-hot 'husky' label. The student learns from these soft targets using a Kullback-Leibler (KL) Divergence loss, often in combination with the standard cross-entropy loss with true labels.

03

Mitigating Catastrophic Forgetting

In continual learning, temperature scaling is used within algorithms like Learning without Forgetting (LwF). When learning a new task, the model's predictions on data from previous tasks are softened with a temperature parameter (T > 1) to create pseudo-soft labels. These labels are then used as distillation targets to regularize training on the new task, penalizing the model if it drifts too far from its old knowledge. This acts as a regularization constraint, helping to preserve performance on past tasks without requiring access to the original training data, thus directly addressing the plasticity-stability trade-off.

04

Improving Contrastive Learning

In self-supervised learning, particularly contrastive frameworks like SimCLR, a temperature parameter (τ) in the InfoNCE loss function controls the concentration of the similarity distribution. A properly tuned τ sharpens the model's ability to distinguish between positive and negative pairs in the embedding space. While conceptually similar, this 'temperature' operates on normalized embeddings (cosine similarity) rather than logits. It is crucial for learning high-quality representations, as it determines how harshly the model penalizes hard negative examples, directly impacting the separation and uniformity of the learned latent space.

05

Controlling Exploration in RL

In reinforcement learning, particularly in policy gradient methods, temperature scaling is applied to the action probability distribution output by the policy network. A higher temperature increases entropy, encouraging exploration by making the policy more stochastic. A lower temperature reduces entropy, making the policy more deterministic and exploitative of known high-reward actions. This parameter is often annealed during training, starting with high exploration (high T) and gradually shifting to exploitation (low T). It's a key hyperparameter in algorithms like Soft Actor-Critic (SAC), where it automatically adjusts to maximize expected reward while maintaining a minimum entropy.

06

Softening Labels for Noisy Datasets

When training with noisy or ambiguous labels, applying temperature scaling (T > 1) to the one-hot labels can create label smoothing. This technique converts hard, potentially incorrect labels into softer, more uncertain distributions (e.g., [0.9, 0.1] -> [0.7, 0.3]). It acts as a form of regularization, preventing the model from becoming overconfident in potentially wrong answers and improving generalization. While distinct from standard label smoothing (which uses a uniform distribution), temperature scaling on logits achieves a similar effect of reducing model overconfidence and can be more adaptive to the specific class relationships present in the data.

COMPARISON

Temperature Scaling vs. Related Concepts

A technical comparison of temperature scaling with other key techniques in knowledge distillation and continual learning, highlighting their primary purpose, mechanism, and typical use cases.

Feature / ConceptTemperature ScalingLogit DistillationFeature DistillationLearning without Forgetting (LwF)

Primary Purpose

Softens teacher model's output distribution to reveal 'dark knowledge'

Trains student to directly match teacher's softened logits

Trains student to replicate teacher's intermediate feature representations

Preserves performance on old tasks while learning new ones

Core Mechanism

Applies temperature parameter T > 1 to softmax function

Minimizes KL divergence between teacher and student output distributions

Minimizes distance (e.g., L2) between teacher and student feature maps

Uses knowledge distillation from the model's own previous outputs

Key Hyperparameter

Temperature (T)

Temperature (T), Distillation Loss Weight (α)

Layer selection, Feature matching loss weight

Distillation loss weight, Learning rate

Requires Stored Past Data?

Common Loss Function

Integrated into cross-entropy or KL divergence

Kullback-Leibler (KL) Divergence

Mean Squared Error (MSE), Cosine Similarity

Cross-entropy (new task) + KL divergence (old tasks)

Typical Use Case

Preparation of teacher logits for any distillation process

General model compression (e.g., BERT -> DistilBERT)

Transferring representational knowledge for performance gain

Task-incremental continual learning without a memory buffer

Modifies Model Architecture?

Computational Overhead

Negligible (forward pass only)

Low (requires teacher forward pass during training)

Moderate (requires forward passes to intermediate layers)

Low (requires forward pass on current model for old tasks)

TEMPERATURE SCALING

Frequently Asked Questions

Temperature scaling is a critical hyperparameter in knowledge distillation and model calibration. These questions address its core mechanics, applications, and relationship to broader machine learning concepts.

Temperature scaling is a post-processing and training technique that applies a scaling parameter (T), called the temperature, to the logits (pre-softmax activations) of a neural network to control the sharpness of its output probability distribution. In the softmax function, temperature is incorporated as softmax(z_i / T), where z_i are the logits. When T = 1, it's the standard softmax. When T > 1, the output probabilities are 'softened' or smoothed, making the distribution more uniform and revealing the model's relative confidence across classes. When T < 1, the distribution becomes 'sharper,' amplifying the highest probability. Its primary uses are in knowledge distillation, where a high temperature transfers 'dark knowledge' from a teacher to a student model, and in model calibration, where a single scalar temperature is optimized on a validation set to better align predicted probabilities with true empirical likelihoods.

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.