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)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. Worked example: 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. Rule: 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.