Derive and Implement the Gradient of Softmax Cross-Entropy

Last updated: November 29, 2026

Quick Overview

Derive the gradient of the softmax cross-entropy loss with respect to the logits, implement it in NumPy for a batch, and verify it numerically.

Meta
Machine Learning
Machine Learning Engineer
Meta
November 29, 2026
Machine Learning Engineer
Technical Screen
Machine Learning
Easy

0

0

0 solved


Derive the gradient of the softmax cross-entropy loss with respect to the logits, implement it in NumPy for a batch, and verify it numerically.

Meta MLE screens sometimes include a short from-scratch exercise to confirm that a candidate understands backpropagation rather than only framework calls. The interviewer checks the derivation, numerical stability, and the habit of gradient checking.

What the Interviewer Expects
  • Derive dL/dz = softmax(z) minus one-hot(y)
  • Use the log-sum-exp trick for stability
  • Average over the batch and scale the gradient accordingly
  • Verify with a finite-difference gradient check
  • Explain why the fused op is preferred over separate softmax and log
Key Topics to Cover
backpropagation
softmax
cross-entropy
numerical stability
gradient checking
How to Approach This
  1. Understand the bias-variance trade-off. High training accuracy but low test accuracy signals overfitting.
  2. Choose evaluation metrics carefully based on the problem. Accuracy alone is often insufficient.
  3. Feature engineering is often more impactful than model selection.
  4. Know when to use tree-based models (tabular data) vs neural networks (unstructured data).
  5. Handle class imbalance with SMOTE, class weights, or appropriate loss functions.
Possible Follow-up Questions
  • How does the gradient change with label smoothing?
  • Why is the gradient bounded, and why does that matter for training?
  • How would you compute this for a 128k-token vocabulary without running out of memory?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Explore ML Interview Prep
Sample Answer
Clarify

Input: logits Z∈RB×CZ \in \mathbb{R}^{B \times C} and integer labels yy. Output: the mean loss over the batch and ∂L/∂Z\partial L / \partial Z with the same shape as ZZ....

Approach

For one example, pj=ezj/∑kezkp_j = e^{z_j} / \sum_k e^{z_k} and L=−log⁡py=−zy+log⁡∑kezkL = -\log p_y = -z_y + \log \sum_k e^{z_k}. Differentiate directly: $\frac{\partial L}{\partial z_j} = -\mathbb{1}[j = y] + \frac{e^{z_j}}{\sum_...


Submit Your Answer
Markdown supported