BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Calculus and gradients6 of 14 in topic

43. Train a ticket classifier: softmax cross-entropy loss and its gradient

MediumCalculus and gradients
Asked atByteDanceGoogle

You are writing the backward pass of a support-ticket classifier that sorts tickets into c intents (billing, refund, login, and so on). Its last layer is softmax followed by cross-entropy, the same final layer every classifier and language model uses. Frameworks hard-code its gradient because it has a short form:

grad = (softmax(logits) - one_hot(labels)) / n

Write softmax_ce_grad(logits, labels) for logits of shape (n, c) and integer labels of shape (n,). Return (loss, grad):
- loss: a Python float, the mean cross-entropy over the n rows: mean of -log softmax(logits)[i, labels[i]].
- grad: shape (n, c), the gradient of that mean loss with respect to the logits. Dividing by n is part of it, because the loss is a mean.

What real training data throws at it:
- A model that is very sure and very wrong. Some tickets are mislabelled, so a row like logits [1000.0, 0.0] with label 1 happens. The loss for that row is 1000, not inf, and the gradient is [1.0, -1.0]. Computing softmax first and then np.log(p) gives log(0) = -inf. Use log-softmax: z - max(z) - log(sum(exp(z - max(z)))).
- Inputs can be Python lists. Do not modify the caller's logits array.

Functiondef softmax_ce_grad(logits, labels)
Play with it

Softmax probabilities behind the cross-entropy gradient

The gradient of cross-entropy with respect to the logits is p − y. Slide a logit and the probabilities you would subtract y from update live.

Sweep the logit of
0%25%50%75%100%-4-2024logit of class 0probability0%25%50%75%100%probabilityclass 054.7%class 133.1%class 212.2%
entropy (nats)
0.953
top class
class 0

Example 1

Input: softmax_ce_grad([[0.0, 0.0]], [1])

Output: (0.6931471805599453, [[0.5, -0.5]]): with two equal logits each class gets 0.5, and the loss is log 2

Example 2

Input: logits = [[1000.0, 0.0]], labels = [0]

Output: (-0.0, [[0.0, 0.0]])

Example 3

Input: logits = [[1000.0, 0.0]], labels = [1]

Output: (1000.0, [[1.0, -1.0]])

Constraints

  • logits has shape (n, c)
  • labels has shape (n,)
  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 8 tests to be accepted.
Hint 1

With p = softmax(logits), the gradient of the mean loss is (p - one_hot(labels)) / n.

Hint 2

Compute log-softmax as z - max - log(sum(exp(z - max))).

Common mistakes
  • Forgetting that is the bug in the buggy version.
Understand the idea

Softmax followed by cross-entropy is the last step of almost every classifier and language model. Its gradient with respect to the logits is beautifully simple: predicted probabilities minus the one-hot label. If the model is already right, the push is small; if it is wrong, the push is large. Worked example, one row, logits [2, 0], label 0. Softmax is [0.881, 0.119]. Loss = -ln(0.881) = 0.127. Gradient = [0.881 - 1, 0.119 - 0] = [-0.119, 0.119]. Because the loss here is the mean over n rows, every row's gradient is then divided by n. For large logits subtract the row max before exp, and compute log-probabilities as z - max - log(sum(exp)) to avoid log of 0.

loss = mean over rows of -log softmax(z)[y]; grad = (softmax(z) - onehot(y)) / n

PyTorch and every other framework hard-code this fused gradient for speed and stability.

Topics
Calculus and gradients
Companies2
  • ByteDance a candidate reported this question ByteDance Machine Learning Engineer Interview | Screna AI
  • Google the topic appears in interview reports Google Interview Prep (Deep-ML)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Derive the gradient of cosine similarity with respect to one vectorMedium
  • Compute the Hessian of the logistic regression lossMedium
  • Choose a step size with Armijo backtracking line searchMedium
  • Differentiate the Gaussian negative log-likelihood with respect to mean and log sigmaMedium
All Calculus and gradients problems
Report
43 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def softmax_ce_grad(logits, labels):
# your code here
pass
​
softmax_ce_grad(_z, _y)[0]

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 8 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS