3.3 Softmax Regression Implementation

Just as we implemented linear regression both from scratch and concisely in Chapter 2, we now build softmax regression on Fashion-MNIST both ways. We start from raw tensors—implementing the rowwise softmax, vectorized cross-entropy loss, and SoftmaxRegressionScratch parameters (W∈R784×10,b∈R10\mathbf{W} \in \mathbb{R}^{784 \times 10}, \mathbf{b} \in \mathbb{R}^{10}) alongside the reusable Classifier(d2l.Module) base class—train to roughly 83%83\% validation accuracy, and inspect what the linear model learned through its 10×1010 \times 10 confusion matrix and 28×2828 \times 28 weight templates. In Section 3.3.5, we then replace manual tensors and probability clamping with a built-in linear layer and a shifted log-sum-exp cross-entropy loss computed directly from raw logits, eliminating floating-point overflow and underflow at once.

3.3.1 The Softmax#

3.3.1.1 Normalizing Each Row#

For a minibatch of nn examples, the logits form an n×qn \times q matrix O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} (Section 3.1.1.4). Softmax normalizes each row independently:

softmax(O)ij=exp⁡(Oij)∑k=1qexp⁡(Oik).(3.3.1)\mathrm{softmax}(\mathbf{O})_{ij} = \frac{\exp(O_{ij})}{\sum_{k=1}^q \exp(O_{ik})}. \tag{3.3.1}

In code, we exponentiate O, sum across columns (axis=1) with keepdims=True so the row sums keep shape (n, 1), and divide via broadcasting:

def softmax(O):
    O_exp = d2l.exp(O)
    return O_exp / d2l.reduce_sum(O_exp, 1, keepdims=True)  # Broadcast

Let us sanity-check softmax on two rows: the cat/chicken/dog logits (1.0,2.2,0.3)(1.0, 2.2, 0.3) from Section 3.1, and a row of three identical zeros.

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.]))

3.3.1.2 Overflow#

Why should you never deploy this three-line softmax formula in production? Because in 32-bit floating point (float32), numbers top out near 3.4×10383.4 \times 10^{38}, so exp⁡(o)\exp(o) overflows to inf as soon as o>88.7o > 88.7. Feed softmax the logits (1000,0,0)(1000, 0, 0) and ∞/∞\infty / \infty evaluates to NaN, even though the true probability distribution is (1,0,0)(1, 0, 0) to machine precision.

As we proved in Section 3.1, softmax is invariant to shifting every logit in a row by the same constant. Subtracting the row maximum omax⁡=max⁡koko_{\max} = \max_k o_k before exponentiating ensures every exponent oj−omax⁡o_j - o_{\max} is ≤0\leq 0 (and the largest is 00), making overflow impossible. Every framework's built-in softmax applies this shift internally:

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.]]))

For our Fashion-MNIST scratch run below, pixel values lie in [0,1][0, 1] and weights stay small, so softmax does not overflow during training; however, shifting alone still leaves very negative logits vulnerable to underflow (exp⁡(−200)=0.0\exp(-200) = 0.0 in float32, turning log⁡0\log 0 into −∞-\infty). In Section 3.3.5 below, we eliminate both hazards permanently by fusing softmax and the logarithm in log space.

3.3.2 Loss and Accuracy#

3.3.2.1 Two Uses of the Logits#

While gradient descent optimizes the smooth cross-entropy loss, humans judge a classifier by its accuracy—the fraction of examples where the top-scoring class matches the true label y(i)y^{(i)}:

accuracy=1n∑i=1n1 ⁣(argmaxjoj(i)=y(i)).(3.3.2)\textrm{accuracy} = \frac{1}{n} \sum_{i=1}^n \mathbf{1}\!\Big(\mathop{\mathrm{argmax}}_j o^{(i)}_j = y^{(i)}\Big). \tag{3.3.2}

Both metrics flow from the exact same logit vector (Figure 3.3.1), and tracking both during validation is essential: if a model becomes overconfident on a few mistakes, its validation cross-entropy loss can rise even while its validation accuracy is still climbing.

Figure 3.3.1:

Training (top) maps logits through softmax to the smooth cross-entropy loss; evaluation (bottom) compares argmax⁡joj\operatorname{argmax}_j o_j against the label yy to compute discrete accuracy.

3.3.2.2 The Classifier Class#

We package this dual-metric validation behavior into Classifier(d2l.Module), the base class for every classification model in the book, starting with validation_step returning both 'loss' and 'acc' on each validation minibatch:

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

Next, we attach accuracy(self, Y_hat, Y, averaged=True) to Classifier: it flattens Y_hat to one row of class scores per example, finds the predicted class index via argmax along axis=1, casts it to Y.dtype, and returns either the mean or per-example float32 equality mask preds == Y:

@d2l.add_to_class(Classifier)
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

Finally, we install plain minibatch SGD at learning rate self.lr as the default configure_optimizers method on d2l.Module so every classifier inherits a working optimizer out of the box:

@d2l.add_to_class(d2l.Module)
def configure_optimizers(self):
    return torch.optim.SGD(self.parameters(), lr=self.lr)

3.3.3 The Model and the Loss#

3.3.3.1 The Parameters and Forward Pass#

Flattening each 28×2828 \times 28 Fashion-MNIST image yields d=784d = 784 input features for q=10q = 10 classes, so SoftmaxRegressionScratch allocates W∈R784×10\mathbf{W} \in \mathbb{R}^{784 \times 10} (initialized from N(0,0.012)\mathcal{N}(0, 0.01^2)) and b∈R10\mathbf{b} \in \mathbb{R}^{10} (initialized to 00), totaling 7,8507{,}850 parameters. Notice a quick sanity check: near-zero initial weights produce near-zero logits, so the untrained model starts close to a uniform prediction (y^j≈0.1\hat{y}_j \approx 0.1) with initial cross-entropy loss near −log⁡(0.1)=log⁡10≈2.30-\log(0.1) = \log 10 \approx 2.30:

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

In forward(self, X), we flatten each image in the minibatch into a row vector of length self.num_inputs (784784) via d2l.reshape(X, (-1, self.num_inputs)) and map the affine logits XW+b\mathbf{X}\mathbf{W} + \mathbf{b} through softmax:

@d2l.add_to_class(SoftmaxRegressionScratch)
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)

3.3.3.2 The Cross-Entropy Loss#

Recall from Section 3.1.2 that l(y,y^)=−log⁡y^yl(\mathbf{y}, \hat{\mathbf{y}}) = -\log \hat{y}_y. Instead of materializing one-hot matrices and taking inner products, we pluck out the true-class probability y^y(i)(i)\hat{y}^{(i)}_{y^{(i)}} for every row ii in one vectorized indexing step:

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

That extracts 0.1 for the first example and 0.5 for the second. Wrapping this in cross_entropy, we average the negative logarithms across the minibatch. Notice the one defensive clamp to 10−1210^{-12} before taking the logarithm: it stops an underflowed zero probability from turning into −∞-\infty, capping the per-example loss at 27.627.6, though clamping also zeroes out the gradient whenever it triggers. Later in this section (Section 3.3.5), we replace this stopgap with a fused loss computed directly from logits.

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)

That yields the mean of −log⁡0.1≈2.30-\log 0.1 \approx 2.30 and −log⁡0.5≈0.69-\log 0.5 \approx 0.69, or roughly 1.50. Let us attach it as the model's loss method:

@d2l.add_to_class(SoftmaxRegressionScratch)
def loss(self, y_hat, y):
    return cross_entropy(y_hat, y)

3.3.4 Training and Evaluation#

3.3.4.1 The Training Run#

Let us train SoftmaxRegressionScratch on Fashion-MNIST for 1010 epochs with minibatch size 256256 and learning rate η=0.1\eta = 0.1:

data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegressionScratch(num_inputs=784, num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)

To score a trained model on an entire dataset split whenever we want, we attach an evaluate(self, model, data, train=False) helper to d2l.Trainer that binds self.val_dataloader to either the validation or training loader and runs self.validate():

@d2l.add_to_class(d2l.Trainer)
def evaluate(self, model, data, train=False):
    """Metrics of `model` on the validation data of `data` (on its training
    data if `train`), averaged over examples."""
    self.train_dataloader = None
    self.val_dataloader = (data.train_dataloader() if train
                           else data.val_dataloader())
    self.prepare_model(model)
    return self.validate()

Averaged across all 10,000 validation images, these metrics match the final points recorded in trainer.history['val_loss'][-1] and trainer.history['val_acc'][-1].

trainer.evaluate(model, data)
{'loss': 0.500844775390625, 'acc': 0.8284}

Our classifier gets roughly 83%83\% of the validation images right; passing train=True evaluates the exact same weights across all 60,00060{,}000 training images:

trainer.evaluate(model, data, train=True)
{'loss': 0.46587086588541665, 'acc': 0.8420666666666666}

After 10 epochs, validation accuracy settles near 83%83\% (varying by ±1%\pm 1\% across random seeds) and training accuracy sits near 84%84\%. That tiny 1%1\% generalization gap reflects the restricted capacity of a linear classifier: 7,8507{,}850 parameters cannot memorize 60,00060{,}000 images (Section 3.5).

3.3.4.2 Misclassified Images#

To see how the model errs, let us pull the first validation minibatch of 256256 images and count the mistakes:

X, y = next(iter(data.val_dataloader()))
preds = d2l.astype(d2l.argmax(model(X), axis=1), y.dtype)
wrong = preds != y
print(f'{int(d2l.reduce_sum(d2l.astype(wrong, d2l.int32)))} of {len(y)} wrong')
35 of 256 wrong

Let us display the first eight misclassified images, showing the true label above the model's prediction (true → pred):

labels = [f'{true}\n→ {pred}' for true, pred in zip(
    data.text_labels(y[wrong]), data.text_labels(preds[wrong]))]
data.visualize([X[wrong], y[wrong]], labels=labels)

3.3.4.3 The Confusion Matrix#

To summarize the error pattern across all 10,00010{,}000 validation images, we tally the 10×1010 \times 10 confusion matrix N∈Rq×q\mathbf{N} \in \mathbb{R}^{q \times q}, where rows index the predicted class c^(m)=argmax⁡joj(m)\hat{c}^{(m)} = \operatorname{argmax}_j o^{(m)}_j and columns index the true class y(m)y^{(m)}:

Nij=∑m=1n1(c^(m)=i) 1(y(m)=j).(3.3.3)N_{ij} = \sum_{m=1}^n \mathbf{1}\big(\hat{c}^{(m)} = i\big)\, \mathbf{1}\big(y^{(m)} = j\big). \tag{3.3.3}

(Placing true classes in the columns and predicted classes in the rows makes column-normalized conditional probabilities multiply cleanly as μ=Cp\boldsymbol{\mu} = \mathbf{C}\mathbf{p} when we study label shift in Section 3.6.) Using one-hot matrices P,Y∈{0,1}n×q\mathbf{P}, \mathbf{Y} \in \{0, 1\}^{n \times q} for a minibatch's predicted and true classes, the product P⊤Y\mathbf{P}^\top\mathbf{Y} accumulates all 100100 counts in a single matrix multiplication per minibatch:

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

All 10,000 validation images are accounted for. Because raw counts depend on class frequency, we normalize each column of N\mathbf{N} by its sum to obtain Cij=Nij/∑i′Ni′jC_{ij} = N_{ij} / \sum_{i'} N_{i'j}, an empirical estimate of the conditional probability P(c^=i∣y=j)P(\hat{c} = i \mid y = j). Each column shows where examples of true class jj land, while the diagonal gives per-class recognition rates. Let us render C\mathbf{C} as a heatmap via d2l.show_heatmaps.

C = N / d2l.reduce_sum(N, 0, keepdims=True)  # Each column sums to 1
names = data.text_labels(range(10))
d2l.show_heatmaps(d2l.reshape(C, (1, 1, 10, 10)), xlabel='true class',
                  ylabel='predicted class', figsize=(4, 4), cmap='Blues',
                  xticklabels=names, yticklabels=names)

Let us also print the five largest off-diagonal entries to spotlight the most frequent confusions:

mistakes = d2l.numpy(N) * (1 - np.eye(10))  # Zero the diagonal
for k in np.argsort(mistakes, axis=None)[::-1][:5]:
    i, j = divmod(int(k), 10)
    print(f'{names[j]} taken for {names[i]}: {int(mistakes[i, j])}')
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

The confusion matrix confirms what our visual inspection in Section 3.2 predicted: trousers, bags, and footwear are recognized ∼90%\sim 90\% of the time or better, whereas the five largest off-diagonal confusions all occur among the four look-alike upper-body tops (T-shirt, pullover, coat, and shirt)—with shirts recognized only about half the time or less because their silhouette sits right in the middle of the other three.

3.3.4.4 The Learned Templates#

Because each logit oj=wj⊤x+bjo_j = \mathbf{w}_j^\top\mathbf{x} + b_j is an inner product between the flattened image x\mathbf{x} and column jj of W\mathbf{W}, reshaping each 784-element column wj\mathbf{w}_j back to 28×2828 \times 28 lets us view the entire classifier as ten visual templates (red = positive weights, blue = negative weights):

W = d2l.numpy(model.W)
templates = W.T.reshape(10, 28, 28)  # Column j of W as an image
v = np.abs(templates).max()
d2l.show_images(templates, 2, 5, titles=names, cmap='RdBu_r', vmin=-v, vmax=v);

Each template is a recognizable ghostly silhouette of its garment—notice the blue negative channel between the trouser legs that penalizes dresses, and the similar torso shapes of the four tops that differ mainly around the collar and sleeves. Because a linear layer can only take a single fixed global dot product per class, subtle local features like collars or buttons cannot overcome overall silhouette overlap; breaking past ∼83%\sim 83\% requires nonlinear hidden layers (Chapter 4) and spatial convolutions (Chapter 6).

3.3.5 Concise Implementation#

Now let us see how deep learning frameworks simplify softmax regression while permanently curing the overflow and underflow hazards of our naive softmax and clamped cross_entropy.

3.3.5.1 Defining the Model#

In SoftmaxRegression(d2l.Classifier), a flattening step and a single built-in fully connected layer with 1010 outputs compute the logits O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} (initialized with N(0,0.012)\mathcal{N}(0, 0.01^2) weights and zero biases to match our scratch baseline). Crucially, forward returns the raw logits O\mathbf{O} directly, without applying softmax:

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)

3.3.5.2 A Stable Cross-Entropy Loss#

Why does SoftmaxRegression.forward stop at the logits instead of returning probabilities? Recall the twin floating-point hazards of computing y^=softmax(o)\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o}) first and −log⁡y^y-\log \hat{y}_y second in float32:

  1. Overflow: exp⁡(o)\exp(o) overflows to inf for o>88.7o > 88.7. Subtracting omax⁡=max⁡koko_{\max} = \max_k o_k from every logit fixes overflow because every shifted exponent ok−omax⁡o_k - o_{\max} is ≤0\leq 0.
  2. Underflow: Even after shifting by omax⁡o_{\max}, any class whose logit sits more than 104104 below omax⁡o_{\max} (such as the second class, label 1 in code, in o=(0,−200,0)\mathbf{o} = (0, -200, 0)) has exp⁡(oy−omax⁡)\exp(o_y - o_{\max}) underflow to exact 0.0 in float32. Taking log⁡(0.0)\log(0.0) then produces -inf (or, with our scratch 1e-12 clamp, caps the loss at 27.627.6 and zeroes out the gradient, leaving the model unable to learn from a confident blunder).

We avoid both overflow and underflow by never materializing intermediate probabilities at all. Combining the logarithm and the shifted softmax algebraically via the LogSumExp trick turns the division into a subtraction:

l(y,o)=log⁡∑k=1qexp⁡(ok)−oy=omax⁡+log⁡∑k=1qexp⁡(ok−omax⁡)−oy.(3.3.4)l(y, \mathbf{o}) = \log \sum_{k=1}^q \exp(o_k) - o_y = o_{\max} + \log \sum_{k=1}^q \exp(o_k - o_{\max}) - o_y. \tag{3.3.4}

Because every shifted exponent ok−omax⁡o_k - o_{\max} is ≤0\leq 0 and at least one equals 00, the sum inside the logarithm lies in [1,q][1, q], and its logarithm in [0,log⁡q][0, \log q]. Neither overflow nor log⁡0\log 0 can occur, and automatic differentiation yields the finite gradient softmax(o)−y\mathrm{softmax}(\mathbf{o}) - \mathbf{y}.

Every framework provides this fused log-sum-exp cross-entropy. We install it once on d2l.Classifier.loss so every classifier in the rest of the book inherits it:

@d2l.add_to_class(d2l.Classifier)
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')

Testing SoftmaxRegression.loss on the extreme logits O = [[1000.0, 0.0, 0.0], [1000.0, 0.0, 0.0]] with true labels y = [0, 1] confirms that the fused LogSumExp implementation returns the exact per-example losses [0., 1000.] without overflow or underflow:

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.])

(Watch out for one classic pitfall: because Classifier.loss expects raw logits and applies log-softmax internally, accidentally placing a softmax at the end of forward applies softmax twice, trapping the training loss above a positive floor; see Exercise 4 below.)

3.3.5.3 Training#

Training SoftmaxRegression with d2l.Trainer takes four lines and reproduces our ∼83%\sim 83\% validation accuracy with rock-solid numerical stability:

data = d2l.FashionMNIST(batch_size=256)
model = SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.fit(model, data)

3.3.6 Summary#

Implementing softmax regression from scratch introduces the reusable Classifier base class, which pairs smooth cross-entropy optimization during training with discrete argmax⁡\operatorname{argmax} accuracy during validation, reaching roughly 83%83\% validation accuracy on Fashion-MNIST in ten epochs. Accumulating one-hot products P⊤Y\mathbf{P}^\top\mathbf{Y} builds the 10×1010 \times 10 confusion matrix and reveals that linear errors concentrate among the four upper-body garments whose learned 28×2828 \times 28 weight templates overlap strongly. Because computing softmax and log separately overflows for large positive logits and underflows to log⁡0\log 0 for large negative logits, our concise implementation returns raw logits from forward and evaluates the shifted log-sum-exp cross-entropy omax⁡+log⁡∑kexp⁡(ok−omax⁡)−oyo_{\max} + \log\sum_k \exp(o_k - o_{\max}) - o_y, guaranteeing finite values and intact gradients across all logit magnitudes.

3.3.7 Exercises#

  1. [code] Cross-entropy from one-hot labels. The cross_entropy of this section selects the correct-class probability by indexing. Implement an alternative that follows the definition −∑jyjlog⁡y^j-\sum_j y_j \log \hat{y}_j literally, by converting y to a one-hot matrix and taking row-wise inner products.

    1. Use it as the loss of SoftmaxRegressionScratch and confirm that training is unchanged.
    2. Time both versions on random probability matrices with 256256 rows and q∈{10,103,105}q \in \{10, 10^3, 10^5\} columns, and state how the memory that each version allocates grows with qq.
    3. Describe a setting in which the inner-product form applies but the indexing form does not.
  2. Large vocabularies. Suppose that softmax regression predicts the next word from a feature vector of dimension d=1024d = 1024. The vocabulary has V=106V = 10^6 words, and each minibatch holds n=256n = 256 examples. List the operations of forward and cross_entropy whose cost grows with VV. Compute the multiply-adds of the matrix product, the float32 memory of W, and the float32 memory of the n×Vn \times V matrix of probabilities, and compare each number with the Fashion-MNIST model of this section.

  3. [code] Templates and class means. The templates are what minibatch SGD made of the pixels it saw.

    1. Train SoftmaxRegressionScratch again with std=0, so that every weight starts at 0 and every class starts with the same logit. Explain why training works all the same, and compare the accuracy and the templates with those of the text.
    2. Show that after one SGD step from zero weights, column jj of W\mathbf{W} is proportional to ∑i(yj(i)−110) x(i)\sum_i \big(y^{(i)}_j - \tfrac{1}{10}\big)\, \mathbf{x}^{(i)} over the first minibatch: the sum of the images of class jj minus a tenth of the sum of all images.
    3. Compute the mean image of each class over the training set and compare it with the trained template of that class, by eye and by the correlation of their pixels. Where do they agree, and where does a template depart from the mean? Explain why a template that merely copied the class mean would confuse the tops even more.
  4. [code] Double softmax. The loss of this section expects logits. Suppose that a model's forward mistakenly ends with a softmax. The loss then receives a probability vector p\mathbf{p} in place of the logits and evaluates −log⁡softmax(p)y-\log \mathrm{softmax}(\mathbf{p})_y.

    1. Find the smallest value this loss can take over all probability vectors p\mathbf{p} and labels yy, as a function of the number of classes qq. Evaluate it for q=10q = 10.
    2. Use the from-scratch softmax defined earlier in this section, which is not part of the d2l package. Subclass SoftmaxRegression so that forward applies this softmax to the logits. Train it with lr=0.1, d2l.FashionMNIST(batch_size=256), and d2l.Trainer(max_epochs=10). Compare its training loss and validation accuracy with those of SoftmaxRegression, and relate the final training loss to the value from the previous step.
  5. [code] Stable softplus. For two classes with logits (x,0)(x, 0), the first term of the loss is log⁡(1+ex)\log(1 + e^x), the softplus of xx.

    1. Plot log⁡(1+ex)\log(1 + e^x) and max⁡(x,0)\max(x, 0) on [−5,5][-5, 5]. Show that the first exceeds the second by at most log⁡2\log 2, at x=0x = 0, and explain in one sentence why log-sum-exp is called a smooth maximum.
    2. Show that log⁡(1+ex)=max⁡(x,0)+log⁡(1+e−∣x∣)\log(1 + e^x) = \max(x, 0) + \log(1 + e^{-|x|}).
    3. In single precision, evaluate the naive expression log(1 + exp(x)), the rewritten expression, and the rewritten expression with log1p in place of log(1 + ...), for x∈{−100,−20,−5,0,5,20,100}x \in \{-100, -20, -5, 0, 5, 20, 100\}. Compare each value with a double-precision reference, and report where each version overflows and where it loses all relative accuracy.
    4. Compute the derivative of the naive expression at x=−20x = -20 by automatic differentiation. Explain why it is accurate although the value of the expression is not, and what this implies for training and for reporting the loss of confidently classified examples.
  6. [code] The gradient survives. For the logits (0,−200,0)(0, -200, 0) with true label 1, the shifted softmax probability of class 1 underflows to 00 in float32, so the clamped scratch loss cross_entropy(softmax(O - O_max), y) hits its 1e-12 floor and has zero gradient with respect to the logits. Pass the same logits and label to the fused loss of SoftmaxRegression and compute the gradient with respect to the logits by automatic differentiation. Compare it with y^−y\hat{\mathbf{y}} - \mathbf{y} from Section 3.1, and explain why the fused loss moves the logit of class 1 while the clamped scratch loss does not.

  7. Number formats. Half-precision formats store a number in 16 bits: FP16 has 5 exponent bits and 10 mantissa bits, BFLOAT16 has 8 and 7, and FP32 has 8 and 23. Determine for each format the largest logit oo for which exp⁡(o)\exp(o) does not overflow. Then explain why a network whose logits reach 20 can be trained in BFLOAT16 but not in FP16 unless its softmax is computed in FP32. Finally, consider the shifted sum of (3.3.4) for q=105q = 10^5 classes, each term at most 1, accumulated in FP16: what goes wrong once the running sum exceeds 2,048, and what does the 10-bit mantissa have to do with it?

Discussions