Padded-Token Smoothed Softmax Loss with Gradients in NumPy
Machine LearningModel answerLast 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 / Cq(c) = eps / Cfor everyc != 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 pdirectly with the log-sum-exp trick. Logits such as±1e4or a very smallTmust not produceinfornan. - Validation: raise
ValueErrorunless 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 invalidepsilonortemperature. - No active tokens: if the mask selects nothing, return
0.0and 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has four steps: scale, compute stable log-probabilities, form the smoothed loss without materializing q, and write the gradient in closed form.
1. Stable log-probabilities
Set s = z / T. For each token subtract the maximum over the class axis, then compute
log p = (s - m) - log(sum(exp(s - m))), with m = max(s).
Every exponent is <= 0, so exp cannot overflow. The largest term is exactly 1, so the sum is at least 1 and the log never reaches -inf. Subtracting a constant does not change a log-softmax, so this affects only the numerics, not the value. Losing classes may underflow to a probability of exactly 0, which is harmless because we only ever use log p, which stays finite.
2. Loss without building q
Since q sums to 1 ((1 - eps) + C * eps/C = 1):
loss_tok = (1 - eps) * (-log p_y) + eps * mean_c(-log p_c)
The first term is the standard NLL, picked out with a gather along the class axis. The second is the uniform-prior term. Sum loss_tok over active positions and divide by N, the number of active tokens.
3. Gradient
Write the per-token loss as -sum_c q_c s_c + (sum_c q_c) * logsumexp(s). Because sum_c q_c = 1 and d logsumexp / d s_j = p_j, the derivative with respect to s_j is p_j - q_j. Then:
- the chain rule through
s = z / Tcontributes a factor1/T; - the mean over active tokens contributes
1/N; - masking multiplies by 0 or 1.
So dL/dz = mask * (p - q) / (T * N).
To avoid allocating q: start from p - eps/C everywhere, then subtract an extra (1 - eps) at the target index.
4. Edge cases
- No active tokens: return
0.0and zeros, before any division, to avoid0/0. - eps = 0: reduces to plain masked cross-entropy.
- Extreme logits or tiny T: handled by the max shift.
- Low precision inputs: compute in float64 and cast the gradient back to the input dtype.
- Empty batch or sequence:
N = 0, so it falls into the no-active-token case.C = 0is rejected. - Targets at masked positions: the spec requires range checking for all positions, so validate them all (real frameworks often use an
ignore_indexinstead).
Code
import numpy as np
from typing import Tuple
def smoothed_masked_nll(logits, targets, mask, epsilon=0.1, temperature=1.0) -> Tuple[float, np.ndarray]:
logits = np.asarray(logits)
targets = np.asarray(targets)
mask = np.asarray(mask)
# validation
if logits.ndim != 3:
raise ValueError("logits must be (B, S, C)")
if targets.ndim != 2 or mask.ndim != 2:
raise ValueError("targets and mask must be (B, S)")
B, S, C = logits.shape
if targets.shape != (B, S) or mask.shape != (B, S):
raise ValueError("shape mismatch")
if C == 0:
raise ValueError("empty vocabulary")
if not np.issubdtype(logits.dtype, np.number) or not np.all(np.isfinite(logits)):
raise ValueError("logits must be finite")
if not np.issubdtype(targets.dtype, np.integer):
raise ValueError("targets must be integers")
if targets.size and (targets.min() < 0 or targets.max() >= C):
raise ValueError("target out of range")
if mask.dtype != np.bool_:
if not np.issubdtype(mask.dtype, np.number) or not np.all((mask == 0) | (mask == 1)):
raise ValueError("mask must be bool or {0, 1}")
if not (np.isfinite(epsilon) and 0.0 <= epsilon < 1.0):
raise ValueError("epsilon must be in [0, 1)")
if not (np.isfinite(temperature) and temperature > 0.0):
raise ValueError("temperature must be > 0")
out_dtype = logits.dtype if np.issubdtype(logits.dtype, np.floating) else np.float64
m = mask.astype(bool)
n = int(m.sum())
if n == 0:
return 0.0, np.zeros((B, S, C), dtype=out_dtype)
# stable log-softmax
s = logits.astype(np.float64) / temperature
shifted = s - s.max(axis=-1, keepdims=True)
log_p = shifted - np.log(np.exp(shifted).sum(axis=-1, keepdims=True))
# loss
idx = targets[..., None].astype(np.int64)
nll = -np.take_along_axis(log_p, idx, axis=-1)[..., 0]
uniform = -log_p.mean(axis=-1)
per_tok = (1.0 - epsilon) * nll + epsilon * uniform
loss = float(per_tok[m].sum() / n)
# gradient (p - q) / (T * N), zero where masked
grad = np.exp(log_p) - epsilon / C
at_t = np.take_along_axis(grad, idx, axis=-1) - (1.0 - epsilon)
np.put_along_axis(grad, idx, at_t, axis=-1)
grad *= m[..., None] / (temperature * n)
return loss, grad.astype(out_dtype)
Complexity
- Time:
O(B * S * C), a small constant number of passes (max, exp-sum, log-probs, gradient). - Space:
O(B * S * C)forlog_pand the gradient, plusO(B * S)for per-token reductions.
Testing
- Run central finite differences in float64 on a tiny input (for example
B=2, S=3, C=5, mixed mask) and compare against the analytic gradient. - Check that every active gradient row sums to about 0 (both
pandqsum to 1) and that masked rows are exactly 0. - Check
eps = 0against a straightforward masked cross-entropy, a fully masked batch, and logits near±1e4.
Reducing memory
The (B, S, C) tensors dominate when the vocabulary is large. A fused kernel can stream over the vocabulary in tiles using the online-softmax recurrence: keep a running max and a rescaled running exp-sum to obtain lse, accumulate sum_c s_c for the smoothing term (since sum_c log p_c = sum_c s_c - C * lse), and capture s_y when its tile is visited. Only lse per token ((B, S), fp32) needs to be saved. In the backward pass, recompute p = exp(s - lse) tile by tile and write (p - q) / (T * N) in place. Going further, chunk over tokens and fuse with the output projection so the full logits tensor never exists.
Common mistakes
- Dividing by
B * Sinstead of the active-token count. - Forgetting the
1/Tfactor in the gradient. - Computing
log(softmax(x))directly, which underflows to-inf. - Letting masked positions leak gradient, or hitting
0/0when the mask is empty. - Applying smoothing mass
epsto the target only instead of spreadingeps/Cover all classes.