Module 16 — Loss Functions
Loss Functions measure how far a model's predictions are from the true target labels. During training, the objective of a Transformer model is to minimize the loss by updating its parameters using backpropagation and optimization algorithms.
Different Transformer architectures use different loss functions depending on the task:
- Cross Entropy Loss → Multi-class Classification & Language Modeling
- Binary Cross Entropy → Binary Classification
- Label Smoothing → Regularized Classification
- KL Divergence → Knowledge Distillation & Distribution Matching
Topics
- Cross Entropy
- Binary Cross Entropy
- Label Smoothing
- KL Divergence
1. Predicted Probability
After the Output Projection layer, logits are converted into probabilities using Softmax.
Formula
where
- = Logit
- = Number of Classes
2. Cross Entropy Loss
Cross Entropy is the most widely used loss function in Transformer models for language modeling and multi-class classification.
Formula
where
- = True label (One-Hot)
- = Predicted probability
Average Cross Entropy
For a batch of size
3. Binary Cross Entropy (BCE)
Binary Cross Entropy is used for binary classification problems.
Formula
where
- = Predicted probability
Batch BCE
4. Label Smoothing
Instead of using hard labels (0 or 1), Label Smoothing distributes a small probability across all classes.
Formula
where
- = Smoothing factor
- = Number of Classes
Example
If
then
- Correct class → 0.9
- Remaining probability → Distributed equally among all other classes
5. Cross Entropy with Label Smoothing
After smoothing,
Formula
This reduces overconfidence and improves model generalization.
6. KL Divergence
KL Divergence measures the difference between two probability distributions.
It is commonly used in
- Knowledge Distillation
- Variational Autoencoders
- Distribution Matching
Formula
where
- = True Distribution
- = Predicted Distribution
7. Language Modeling Loss
For autoregressive language models (GPT)
Formula
where
- = Current token
- = Previous tokens
8. Masked Language Modeling Loss
For BERT
Only masked tokens contribute to the loss.
Formula
where
- = Masked token positions
9. Sequence-to-Sequence Loss
For encoder-decoder models
Formula
where
- = Input sequence
- = Target sequence
10. Total Training Objective
The optimization objective is
where
- = Model parameters
The optimizer updates the parameters to minimize the loss.
11. Matrix Dimensions
Suppose
- Batch Size =
- Vocabulary Size =
Logits
Probabilities
Labels
Loss
12. Applications
These loss functions are used in
- GPT
- GPT-2
- GPT-3
- GPT-4
- BERT
- RoBERTa
- ALBERT
- T5
- BART
- LLaMA
- Gemma
- Qwen
- Mistral
- DeepSeek
- Phi
- Vision Transformers
- Large Language Models (LLMs)
Summary
| Concept | Formula |
|---|---|
| Cross Entropy |