KatInterview

Padded-Token Smoothed Softmax Loss with Gradients in NumPy

Machine LearningModel answer
MediumModel answerMachine Learningcross-entropylabel-smoothingnumpy

Last updated

Write a stable NumPy loss for sequence models that skips padded positions, smooths the target distribution, rescales logits by temperature, and returns the exact gradient with respect to the logits.

Task

When training a next-token prediction model, batches are padded to a common length. The loss must ignore the padded positions, discourage over-confident predictions, and stay finite even for very large logits.

Implement smoothed_masked_nll using only NumPy. It returns the mean smoothed cross-entropy over the real (unmasked) tokens, together with the exact gradient of that mean with respect to the input logits.

Definitions

Let C be the vocabulary size and eps the smoothing strength, with 0 <= eps < 1. For a token whose true class is y, the soft target distribution is:

  • q(y) = (1 - eps) + eps / C
  • q(c) = eps / C for every c != y

With temperature T > 0, the scaled logits are s = z / T and the predicted distribution is p = softmax(s).

The loss at one active token is

-sum_c q(c) * log p(c) = (1 - eps) * (-log p(y)) + eps * mean_c(-log p(c))

The final loss is the average of this quantity over positions where mask is true. If no position is active, the loss is 0.0.

Signature

import numpy as np
from typing import Tuple

def smoothed_masked_nll(
    logits: np.ndarray,       # (B, S, C), float32 or float64
    targets: np.ndarray,      # (B, S), integer class ids
    mask: np.ndarray,         # (B, S), bool or values in {0, 1}
    epsilon: float = 0.1,
    temperature: float = 1.0,
) -> Tuple[float, np.ndarray]:
    ...

Return (loss, grad_logits), where grad_logits has shape (B, S, C).

Requirements

  • Stability: compute log p directly with the log-sum-exp trick. Logits such as ±1e4 or a very small T must not produce inf or nan.
  • Validation: raise ValueError unless all of the following hold: logits.ndim == 3, targets.ndim == 2, mask.ndim == 2, the batch and sequence sizes agree, 0 <= targets < C, and the logits are finite. Also reject an invalid epsilon or temperature.
  • No active tokens: if the mask selects nothing, return 0.0 and an all-zero gradient of shape (B, S, C).
  • Gradient: it must be the exact derivative of the returned loss with respect to logits (not the scaled logits). Masked positions must have gradient exactly zero.

What to discuss

Briefly explain your derivation, the complexity, how you would test the gradient, and how you would cut the memory use of the (B, S, C) intermediates.

Hints

Hint 1

Because q sums to 1, you never need to build q. The loss splits into an ordinary negative log-likelihood term weighted by (1 - eps) plus a uniform term weighted by eps, which is the mean of -log p over all classes.

Hint 2

Softmax cross-entropy against any target distribution that sums to 1 has gradient (p - q) with respect to the scaled logits. Then apply the chain rule for the division by T and for the average over active tokens.

Hint 3

Handle the empty-mask case before dividing by the token count, and divide by the number of active tokens, not by B*S. To check your work, compare against central finite differences in float64, and confirm that each active gradient row sums to about zero.