Implement Numerically Stable Softmax and Log-Sum-Exp for Token Logits
Last updated: November 29, 2026
Quick Overview
Write softmax, log-sum-exp, and cross-entropy for a vector of logits so they never overflow or underflow, and explain why the naive formula fails on large language model logits.
0
0
0 solved
Write softmax, log-sum-exp, and cross-entropy for a vector of logits so they never overflow or underflow, and explain why the naive formula fails on large language model logits.
Google interviewers for ML infrastructure and TPU kernel teams use this as a warm-up to see whether a candidate has actually debugged NaN losses. It checks floating-point intuition and whether you know where the max-subtraction trick belongs in a training loss.
What the Interviewer Expects
- Explains that exp overflows for large logits and underflows for very negative ones
- Subtracts the max before exponentiating and proves the result is unchanged
- Computes cross-entropy from log-sum-exp without materializing probabilities
- Handles temperature and masked (negative infinity) logits
- Mentions low-precision formats such as bfloat16
Key Topics to Cover
How to Approach This
- Understand the bias-variance trade-off. High training accuracy but low test accuracy signals overfitting.
- Choose evaluation metrics carefully based on the problem. Accuracy alone is often insufficient.
- Feature engineering is often more impactful than model selection.
- Know when to use tree-based models (tabular data) vs neural networks (unstructured data).
- Handle class imbalance with SMOTE, class weights, or appropriate loss functions.
Possible Follow-up Questions
- Why do training frameworks fuse softmax with cross-entropy?
- How would you compute this over a 256k vocabulary split across devices?
- What happens to the gradient of cross-entropy with respect to the logits?
- How does temperature change the entropy of the distribution?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Explore ML Interview PrepSample Answer
Clarify
Input is a list of logits, possibly in the thousands for a badly scaled model, possibly with masked entries set to negative infinity (padding or disallowed tokens). I need softmax probabilities, log-s...
Approach
Softmax is invariant to adding a constant to every logit: . Choosing makes the largest exponent , so ...