273. Backprop a 2-layer ReLU MLP with softmax cross-entropy, ignored labels and weight decay
Language-model losses skip padded or prompt tokens with an ignore label, and add weight decay on matrices but not biases. Getting the averaging right is where hand-written backward passes go wrong.
Write mlp_ce_grads(x, y, W1, b1, W2, b2, wd=0.0, ignore_index=-100):
- x is (n, d), y is a length-n list of class ids or ignore_index.
- h = relu(x @ W1 + b1) (relu'(0) = 0), logits = h @ W2 + b2 of shape (n, C).
- Let V be the rows with y != ignore_index. ce = mean over V of -log_softmax(logits[i])[y[i]]. If V is empty, ce = 0.0 and it contributes no gradient.
- loss = ce + 0.5 * wd * (sum(W1 ** 2) + sum(W2 ** 2)). No decay on b1 or b2.
Return a dict with "loss" (float) and "W1", "b1", "W2", "b2" (gradients of loss, same shapes as the parameters).
Use a stable softmax.
def mlp_ce_grads(x, y, W1, b1, W2, b2, wd=0.0, ignore_index=-100)Example 1
Input: mlp_ce_grads([[1.0, 0.0]], [0], [[1.0], [0.0]], [0.0], [[1.0, 0.0]], [0.0, 0.0])
Output: {'loss': 0.3133, 'W1': [[-0.2689], [0.0]], 'b1': [-0.2689], 'W2': [[-0.2689, 0.2689]], 'b2': [-0.2689, 0.2689]}
Constraints
b2has shape(n, C)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
dlogits = (softmax - one_hot) / |V| on valid rows and 0 on ignored rows.
Hint 2
Then dW2 = h.T @ dlogits + wd * W2, db2 = dlogits.sum(0), dh = dlogits @ W2.T, da = dh * (pre-activation > 0), dW1 = x.T @ da + wd * W1, db1 = da.sum(0).
Common mistakes
- The buggy version divides by n, the full batch size.
Understand the idea
Language model training marks padding or prompt tokens with an ignore label so they add nothing to the loss. The mean must then divide by the number of valid rows, not the full batch, and every gradient shares that same denominator.
3 rows, one labelled ignore_index, so V has 2 rows. If a valid row has logits [0, 0] and target 0, softmax is [0.5, 0.5] and its logit gradient is (p - one_hot) / 2 = [-0.25, 0.25]. The ignored row gets a zero gradient.
dlogits = (softmax - one_hot) / |V| on valid rows, 0 elsewhere; dW2 = h^T dlogits + wd * W2; db2 = column sums of dlogits; dh = dlogits W2^T; dz = dh where the pre-activation is above 0, else 0; dW1 = x^T dz + wd * W1; db1 = column sums of dz
The loss is the mean cross-entropy plus 0.5 * wd * (sum W1^2 + sum W2^2); biases get no decay. If V is empty, cross-entropy is 0 with no gradient. This is exactly what happens under the hood in supervised fine-tuning with masked prompt tokens.
Topics
Companies1
- Anthropic a candidate reported this question ML Coding at Each Company (CircleCoder)
From public interview reports and guides. Not affiliated with or endorsed by these companies.