Take one gradient step for softmax regression

Why it matters The LM head of every transformer is softmax regression over the vocabulary.

Multinomial logistic regression is a linear layer followed by softmax and cross-entropy.

Write softmax_reg_step(W, X, y, lr). W is (d, k), X is (n, d), y is (n,) integer classes. Compute P = softmax(X W) row by row, the mean cross-entropy loss, the gradient G = X^T (P - Y) / n where Y is one-hot, and return (new_W, loss) with new_W = W - lr * G. The loss is computed before the update.

Signaturedef softmax_reg_step(W, X, y, lr)

Example

W = zeros (1, 2), X = [[1]], y = [0], lr = 1 gives loss log 2 = 0.6931 and new_W [[0.5, -0.5]].

Understand the idea

Softmax regression is a linear layer, then softmax, then cross-entropy, the simplest multi-class classifier. The gradient has a clean form: for each row, predicted probabilities minus the one-hot label, mapped back to the weights through X^T. Worked example: W = zeros of shape (2, 2), X = [[1, 2]], y = [1], lr = 0.5. Logits [0, 0], P = [0.5, 0.5], loss = -ln 0.5 = 0.6931. P - Y = [0.5, -0.5]. G = X^T (P - Y) / 1 = [[0.5, -0.5], [1.0, -1.0]]. new_W = W - 0.5 * G = [[-0.25, 0.25], [-0.5, 0.5]]. The column for the true class grows, as expected. Rule: logits = X W; subtract each row's max before exp for stability; P = softmax per row; loss = mean of -log P[i, y_i], computed before the update; G = X^T (P - one_hot(y)) / n; new_W = W - lr * G. Flipping P - Y to Y - P makes the step go uphill. This is also exactly the last layer of most neural classifiers and of an LLM's output head.

Shapes and data flow

X (n, d) @ W (d, k) -> logits (n, k)
P - Y (n, k), X^T (d, n) @ (n, k) -> G (d, k)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplesoftmax_reg_step(np.zeros((1, 2)), [[1]], [0], 1.0)
  • Sample 2: randomsoftmax_reg_step(_W, _X, _y, 0.1)
  • Test 3: three classessoftmax_reg_step(np.ones((2, 3)), [[1, 0], [0, 1], [1, 1]], [2, 0, 1], 0.5)