def softmax(O):
O_exp = d2l.exp(O)
return O_exp / d2l.reduce_sum(O_exp, 1, keepdims=True) # BroadcastDive into Deep Learning · §3.3
Softmax Regression Implementation: From Scratch to LogSumExp
rowwise softmax · float32 overflow & underflow · Classifier base class · confusion matrix · templates · fused LogSumExp loss
The Numerical & Systems Motivation
Building softmax regression on Fashion-MNIST (d = 784, q = 10, 7{,}850 parameters) requires solving two immediate problems:
float32 overflows to inf above \exp(88.7) \approx 3.4 \times 10^{38} (\infty / \infty = \texttt{NaN}) and underflows to 0.0 below \exp(-104) (-\log 0 = +\infty).From-Scratch Softmax
Given a minibatch of logits \mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} \in \mathbb{R}^{n \times q}, softmax normalizes each row independently:
\mathrm{softmax}(\mathbf{O})_{ij} = \frac{\exp(O_{ij})}{\sum_{k=1}^q \exp(O_{ik})}
keepdims=True): Preserves shape (n, 1) so division broadcasts each row sum across all q columns.Sanity Check
Testing softmax on our cat/chicken/dog logits (1.0, 2.2, 0.3) from §3.1 alongside a row of three identical zeros confirms row normalization:
(tensor([[0.2076, 0.6893, 0.1031],
[0.3333, 0.3333, 0.3333]]),
tensor([1., 1.]))
Overflow Safeguard
Subtracting the row maximum o_{\max} = \max_k o_k ensures every shifted logit o_j - o_{\max} \le 0 (and the largest is 0):
(tensor([[nan, 0., 0.]]), tensor([[1., 0., 0.]]), tensor([[1., 0., 0.]]))
exp overflow, but if o_y - o_{\max} < -104, \exp(o_y - o_{\max}) still underflows to 0.0, causing -\log \hat{y}_y = +\infty.Training vs. Evaluation Metrics
Both training and evaluation consume the exact same logit matrix \mathbf{O} \in \mathbb{R}^{n \times q}, but take different branches:
Reusable Object-Oriented Abstraction
We package dual-metric validation into Classifier(d2l.Module), the base class for every classification network in the book:
def accuracy(self, Y_hat, Y, averaged=True):
"""Compute the fraction of correct predictions."""
Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
preds = d2l.astype(d2l.argmax(Y_hat, axis=1), Y.dtype)
compare = d2l.astype(preds == d2l.reshape(Y, (-1,)), d2l.float32)
return d2l.reduce_mean(compare) if averaged else compareaccuracy flattens batch axes to (-1, q), casts argmax(axis=1) to Y.dtype, and averages the indicator tensor.Optimizer Configuration
Because nearly every baseline model trains with minibatch stochastic gradient descent at learning rate self.lr, we attach a default configure_optimizers method directly to d2l.Module:
7,850 Learnable Parameters
Flattening a 28 \times 28 Fashion-MNIST image yields d = 784 features for q = 10 garment classes (\mathbf{W} \in \mathbb{R}^{784 \times 10} from \mathcal{N}(0, 0.01^2), \mathbf{b} = \mathbf{0} \in \mathbb{R}^{10}):
class SoftmaxRegressionScratch(Classifier):
"""Softmax regression implemented from scratch."""
def __init__(self, num_inputs, num_outputs, lr, std=0.01):
super().__init__()
self.save_hyperparameters()
self.W = nn.Parameter(d2l.normal(0, std, (num_inputs, num_outputs)))
self.b = nn.Parameter(d2l.zeros(num_outputs))7,850 Learnable Parameters
O(n) Indexing vs. O(nq) One-Hot Products
Instead of an n \times q one-hot matrix, one O(n) integer-indexing gather plucks out each row’s \hat{Y}_{i, y_i}:
tensor([0.1000, 0.5000])
tensor(1.4979)
O(n) Indexing vs. O(nq) One-Hot Products
1e-12 clamp is only a stopgap: Wherever \max(\hat{y}_y, 10^{-12}) triggers, the derivative is zero, killing the gradient on the worst mistakes.10 Epochs of Minibatch SGD
We train SoftmaxRegressionScratch for 10 epochs on Fashion-MNIST with minibatch size n = 256 and learning rate \eta = 0.1:
{'loss': 0.500844775390625, 'acc': 0.8284}
{'loss': 0.46587086588541665, 'acc': 0.8420666666666666}
Qualitative Error Analysis
In the first validation minibatch of 256 images, roughly 40 garments are misclassified. Plotting the first eight mistakes (true → predicted) reveals a clear visual pattern:
35 of 256 wrong
Quantitative Error Breakdown
One-hot matrices \mathbf{P}, \mathbf{Y} \in \{0, 1\}^{n \times 10} tally all predictions via \mathbf{N} \mathrel{+}= \mathbf{P}^\top\mathbf{Y}:
def one_hot(y, q):
"""Rows of the q x q identity matrix, one per class index in y."""
return d2l.astype(d2l.reshape(y, (-1, 1)) == d2l.arange(q, dtype=y.dtype),
d2l.float32)
N = d2l.zeros((10, 10))
for X, y in data.val_dataloader():
P = one_hot(d2l.argmax(model(X), axis=1), 10)
N += d2l.matmul(d2l.transpose(P), one_hot(y, 10))
int(d2l.reduce_sum(N))shirt taken for pullover: 207
coat taken for pullover: 192
shirt taken for T-shirt: 192
shirt taken for coat: 151
pullover taken for coat: 102
Where the Linear Model Struggles
Plotting C_{ij} = N_{ij} / \sum_{i'} N_{i'j} as a 10 \times 10 heatmap shows exactly where each true garment category lands:
1), bags (8), sandals (5), sneakers (7), and ankle boots (9) have distinct silhouettes and bright diagonal cells.0), pullover (2), coat (4), and shirt (6).What a Linear Classifier Learns
Because o_j = \mathbf{w}_j^\top\mathbf{x} + b_j is an inner product between image \mathbf{x} and column j of \mathbf{W}, reshaping each 784-element column \mathbf{w}_j to 28 \times 28 reveals ten spatial templates (red > 0, blue < 0):
Global template matching: Notice the negative blue channel between the trouser legs that penalizes dresses, and the nearly identical red torso blobs of the four tops. Because a linear layer takes only one global dot product per class, local collar or button details cannot overcome overall silhouette overlap.
Concise Framework Implementation
In SoftmaxRegression(d2l.Classifier), a flattening layer and a single built-in linear layer replace manual parameter management:
class SoftmaxRegression(d2l.Classifier):
"""The softmax regression model."""
def __init__(self, num_outputs, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.Flatten(),
nn.LazyLinear(num_outputs))
def weight_init(self, module):
# The Trainer calls this after the lazy layer has learned its shape
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=0.01)
nn.init.zeros_(module.bias)
def forward(self, X):
return self.net(X)Concise Framework Implementation
forward returns raw logits \mathbf{O}: Both Classifier.accuracy (\operatorname{argmax}_j O_{ij}) and fused cross-entropy consume unnormalized logits directly. Putting softmax inside forward would apply softmax twice.Eliminating Both Overflow and Underflow
Fusing \mathrm{softmax}(\mathbf{o})_y and -\log(\cdot) algebraically in log space and shifting by o_{\max} = \max_k o_k:
l(y, \mathbf{o}) = o_{\max} + \log \sum_{k=1}^q \exp(o_k - o_{\max}) - o_y
Framework Logit Losses
We install the framework’s fused LogSumExp cross-entropy on d2l.Classifier.loss and test it on extreme logits (1000, 0, 0):
tensor([ -0., 1000.])
End-to-End Verification
Training SoftmaxRegression with d2l.Trainer takes four lines of code and reproduces \sim 83\% validation accuracy with complete numerical stability across all logit magnitudes:
SoftmaxRegressionScratch.self.net with multilayer perceptrons or convolutional networks requires zero changes to Classifier, loss, or Trainer.Concept Check
Test your understanding of numerical stability and implementation pitfalls:
softmax return on \mathbf{o} = (-1000, -1000, -1000) in float32, and what does the shifted formula return?softmax at the end of forward before passing the output to the framework’s cross-entropy loss. For q = 10 classes, what is the lowest loss value the model can ever reach, even when it predicts a deterministic one-hot vector \mathbf{p} = (1, 0, \ldots, 0)?float32 memory do the output weight matrix \mathbf{W} \in \mathbb{R}^{d \times q} and logit matrix \mathbf{O} \in \mathbb{R}^{n \times q} occupy?Answers: (1) Unshifted: \exp(-1000) = 0.0 in all three slots, giving 0.0 / 0.0 = \texttt{NaN}; shifted by o_{\max} = -1000: \mathrm{softmax}(0, 0, 0) = (1/3, 1/3, 1/3). (2) Feeding \mathbf{p} = (1, 0, \ldots, 0) into -\log\mathrm{softmax}(\mathbf{p})_1 gives -\log(e^1 / (e^1 + 9e^0)) = \log(e + 9) - 1 \approx 1.46\text{ nats}, trapping the training loss above 1.46. (3) \mathbf{W} takes 1024 \times 10^6 \times 4\text{ B} \approx 4.10\text{ GB}, and a single batch of logits \mathbf{O} takes 256 \times 10^6 \times 4\text{ B} \approx 1.02\text{ GB}.
Section Summary
| Component | From-Scratch Implementation | Concise Framework Implementation |
|---|---|---|
| Parameters | Manual \mathbf{W} \in \mathbb{R}^{784\times 10},\; \mathbf{b} \in \mathbb{R}^{10} (7{,}850 params) | Built-in linear layer with 10 outputs |
| Forward output | Probability matrix \hat{\mathbf{Y}} = \mathrm{softmax}(\mathbf{X}\mathbf{W}+\mathbf{b}) | Raw logit matrix \mathbf{O} = \mathbf{X}\mathbf{W}+\mathbf{b} (no softmax) |
| Cross-entropy loss | -\log \max(\hat{Y}_{i, y_i}, 10^{-12}) (clamped indexing) | Fused LogSumExp: o_{\max} + \log\sum_k \exp(o_k - o_{\max}) - o_y |
| Numerical stability | Overflows for o > 88.7; clamp zeroes gradient on underflow | Immune to overflow & underflow; exact gradient \mathrm{softmax}(\mathbf{o}) - \mathbf{y} |
Classifier base class |
Logs validation 'loss' and 'acc'; default SGD optimizer |
Inherited unchanged by all classifiers across the book |
| Diagnostics (83\% val) | 10\times 10 confusion matrix \mathbf{N} = \sum \mathbf{P}^\top\mathbf{Y} & 28\times 28 templates | Confusions concentrate among the 4 overlapping upper-body tops |