Softmax Regression Implementation

Dive 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

Why Naive Softmax & Cross-Entropy Break in Float32

The Numerical & Systems Motivation

Building softmax regression on Fashion-MNIST (d = 784, q = 10, 7{,}850 parameters) requires solving two immediate problems:

  • Float32 overflow & underflow: 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).
  • Dual-metric model abstraction: Every classifier optimizes smooth cross-entropy during backprop while logging discrete \operatorname{argmax} accuracy across variable-sized validation minibatches.

Rowwise Softmax via Broadcasting

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})}

def softmax(O):
    O_exp = d2l.exp(O)
    return O_exp / d2l.reduce_sum(O_exp, 1, keepdims=True)  # Broadcast
  • Keeping the reduced axis (keepdims=True): Preserves shape (n, 1) so division broadcasts each row sum across all q columns.

Verifying Rowwise Softmax on Test Logits

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:

O = d2l.tensor([[1.0, 2.2, 0.3], [0.0, 0.0, 0.0]])
Y_hat = softmax(O)
Y_hat, d2l.reduce_sum(Y_hat, 1)
(tensor([[0.2076, 0.6893, 0.1031],
         [0.3333, 0.3333, 0.3333]]),
 tensor([1., 1.]))
  • Expected outputs: The first row reproduces (0.21, 0.69, 0.10), the second row yields the uniform distribution (1/3, 1/3, 1/3), and every row sum equals 1.0.

Subtracting the Row Maximum Prevents Overflow

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):

O = d2l.tensor([[1000.0, 0.0, 0.0]])
O_max = O.amax(dim=1, keepdim=True)
softmax(O), softmax(O - O_max), torch.softmax(O, dim=1)
(tensor([[nan, 0., 0.]]), tensor([[1., 0., 0.]]), tensor([[1., 0., 0.]]))
  • Why shifting alone is not enough for the loss: Subtracting o_{\max} cures 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.

Two Branches from One Logit Vector: Loss vs. Accuracy

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:

  • Training branch (top): Passes logits through softmax to compute the smooth, differentiable cross-entropy loss l(\mathbf{y}, \hat{\mathbf{y}}).
  • Evaluation branch (bottom): Takes \operatorname{argmax}_j o_j directly to compute discrete accuracy: \mathrm{accuracy} = \frac{1}{n}\sum_{i=1}^n \mathbf{1}\!\Big(\operatorname*{argmax}_j o^{(i)}_j = y^{(i)}\Big)
  • Why track both? If a model becomes overconfident on a few hard validation examples, its validation loss can rise even while validation accuracy is still improving.

The Classifier Base Class and Vectorized Accuracy

Reusable Object-Oriented Abstraction

We package dual-metric validation into Classifier(d2l.Module), the base class for every classification network in the book:

class Classifier(d2l.Module):
    """The base class of classification models."""
    def validation_step(self, batch):
        Y_hat = self(*batch[:-1])
        return {'loss': self.loss(Y_hat, batch[-1]),
                'acc': self.accuracy(Y_hat, batch[-1])}
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 compare
  • Type-safe comparison: accuracy flattens batch axes to (-1, q), casts argmax(axis=1) to Y.dtype, and averages the indicator tensor.

Default Minibatch SGD Optimizer on Module

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:

def configure_optimizers(self):
    return torch.optim.SGD(self.parameters(), lr=self.lr)
  • Automatic parameter discovery: The framework optimizer automatically collects all registered learnable parameters of the model.

Registering Scratch Parameters and the Forward Pass

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))
def forward(self, X):
    X = d2l.reshape(X, (-1, self.num_inputs))  # One flattened image per row
    return softmax(d2l.matmul(X, self.W) + self.b)

Parameter Shapes and the Initial-Loss Check

7,850 Learnable Parameters

  • Parameter count: 784 \times 10 weights plus 10 biases give 7{,}850 learnable parameters.
  • Initial-loss sanity check: With \mathbf{W} \approx \mathbf{0}, \hat{y}_j \approx 0.1 and initial cross-entropy sits near -\log(0.1) = \log 10 \approx 2.30\text{ nats}.

Vectorized Cross-Entropy by Integer Indexing

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}:

y = d2l.tensor([0, 2])
y_hat = d2l.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]
tensor([0.1000, 0.5000])
def cross_entropy(y_hat, y):
    # Tiny clip to keep log finite when softmax outputs underflow to 0.
    p = y_hat[list(range(len(y_hat))), y].clamp(min=1e-12)
    return -d2l.reduce_mean(d2l.log(p))

cross_entropy(y_hat, y)
tensor(1.4979)

Gather vs. One-Hot, and the Clamp’s Blind Spot

O(n) Indexing vs. O(nq) One-Hot Products

  • Linear cost: The gather touches n entries, while a one-hot product multiplies all nq entries, almost all of them zero.
  • Why the 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.

Training Softmax Regression from Scratch

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:

  • Rapid convergence: Validation accuracy climbs past 75\% in the first epoch and settles near 83\% by epoch 10, while validation cross-entropy loss drops from \approx 2.30 to \approx 0.50 (and training loss to \approx 0.46).
  • Evaluation on full splits: Evaluating across all 10{,}000 validation images and 60{,}000 training images shows a tiny \sim 1\% generalization gap:
{'loss': 0.500844775390625, 'acc': 0.8284}
{'loss': 0.46587086588541665, 'acc': 0.8420666666666666}

Inspecting Individual Misclassified Garments

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

  • Silhouette confusion: Nearly every error swaps two upper-body tops (shirt, pullover, coat, T-shirt) or two footwear items that share a similar global pixel outline.

Accumulating the 10 × 10 Confusion Matrix

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
  • Columns = true class: Normalizing columns gives C_{ij} = P(\hat{c} = i \mid y = j).

Visualizing the Column-Normalized Confusion Matrix

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:

  • High-accuracy classes (\ge 90\%): Trousers (1), bags (8), sandals (5), sneakers (7), and ankle boots (9) have distinct silhouettes and bright diagonal cells.
  • The upper-body bottleneck: The five largest off-diagonal confusions all occur among T-shirt (0), pullover (2), coat (4), and shirt (6).
  • Shirts are recognized only about half the time or less: Their boxy torso overlaps all three rival tops.

Visualizing the Learned Columns of W as Templates

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 Model: Returning Raw Logits

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)

Why forward Stops at the Logits

Concise Framework Implementation

  • Critical invariant — 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.

The LogSumExp Trick: Fusing Softmax and Logarithm

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

  • Overflow impossible: Every o_k - o_{\max} \le 0, so \exp(o_k - o_{\max}) \in (0, 1].
  • Underflow \log(0) impossible: At k = \operatorname{argmax} o_k, \exp(0) = 1, trapping the sum inside [1, q] and its log inside [0, \log q] with exact gradient \mathrm{softmax}(\mathbf{o}) - \mathbf{y}.

Installing Fused Cross-Entropy on Classifier

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):

def loss(self, Y_hat, Y, averaged=True):
    Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
    Y = d2l.reshape(Y, (-1,))
    return F.cross_entropy(
        Y_hat, Y, reduction='mean' if averaged else 'none')
O = d2l.tensor([[1000.0, 0.0, 0.0], [1000.0, 0.0, 0.0]])
y = d2l.tensor([0, 1])
SoftmaxRegression(num_outputs=3, lr=0.1).loss(O, y, averaged=False)
tensor([  -0., 1000.])

Concise Training Run on Fashion-MNIST

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:

  • Identical mathematical trajectory: Because weights start from \mathcal{N}(0, 0.01^2) and biases at 0, the concise model follows the exact same optimization dynamics as SoftmaxRegressionScratch.
  • Foundation for Chapters 4–8: Replacing the single linear layer inside self.net with multilayer perceptrons or convolutional networks requires zero changes to Classifier, loss, or Trainer.

Concept Check: Underflow, Double Softmax & Scaling

Concept Check

Test your understanding of numerical stability and implementation pitfalls:

  1. Extreme negative logits: What does our unshifted scratch softmax return on \mathbf{o} = (-1000, -1000, -1000) in float32, and what does the shifted formula return?
  2. The double-softmax bug: Suppose a developer accidentally puts 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)?
  3. Vocabulary scaling: In a language model with hidden size d = 1024, batch size n = 256, and vocabulary q = 10^6 tokens, how much 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}.

Summary: From-Scratch vs. Concise Softmax Regression

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