BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Evaluation metrics24 of 33 in topic

175. Batch LM cross-entropy with ignore index, perplexity and gradient

HardEvaluation metrics Pro
Asked atOpenAI

Why it matters Every LM training step and every perplexity number comes from this computation, and the ignore index is how padding and prompts are excluded.

Training and evaluating a language model both start from the same quantity: the mean cross-entropy over all real target tokens in a (B, T, V) batch, skipping ignored positions.

Write lm_cross_entropy(logits, targets, ignore=-100). logits is (B, T, V); targets is (B, T) with ignore at positions that do not count (at least one position counts). Let N be the number of counted positions. Return (loss, ppl, dlogits):
- loss = mean over counted positions of -log_softmax(logits)[target] (stable)
- ppl = exp(loss)
- dlogits (B, T, V) = (softmax - onehot(target)) / N at counted positions and 0 at ignored positions.

Functiondef lm_cross_entropy(logits, targets, ignore=-100)

Example 1

Input: lm_cross_entropy(np.zeros((1, 2, 2)), [[0, -100]])

Output: (0.6931, 2.0, [[[-0.5, 0.5], [0, 0]]])

Example 2

Input: logits = LG, targets = TG

Output: (1.128201, 3.090092, [[[0.044664, -0.169426, 0.070752, 0.05401], [0.0, 0.0, 0.0, 0.0], [0.019465, 0.151202, 0.031457, -0.202124]], [[-0.048377, 0.016061, 0.011898, 0.020418], [0.154292, 0.024999, -0.194917, 0.015625], [0.0, 0.0, 0.0, 0.0]]])

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Flatten to (B*T, V), keep a boolean mask, and divide by the mask count, not B*T.

Hint 2

Replace ignored targets with 0 before indexing, then mask.

Hint 3

Divide by N, the number of counted tokens.

Hint 4

Zero the gradient rows of ignored positions.

Common mistakes
  • Averaging over all positions including padding.
  • Indexing with -100 directly, which silently picks the last vocabulary entry.
Understand the idea

Cross-entropy measures how surprised the model is by the true next token: -log of the probability it gave that token. Averaging over many tokens gives the loss, and exp(loss) is perplexity, roughly "how many tokens the model is choosing between".

Worked example

two positions, vocabulary of 2, all logits 0, so each token has probability 0.5. Position 0 has target 0; position 1 is padding (-100). Only one position counts, so the loss is -ln 0.5 = 0.693 and the perplexity is 2. The gradient at position 0 is softmax minus one-hot: [0.5 - 1, 0.5] = [-0.5, 0.5], divided by N = 1. Position 1 gets zero gradient.

loss = (1 / N) sum over counted (b, t) of -log softmax(z_bt)[y_bt]; dz = (softmax - onehot) / N on counted positions

Dividing by N, not B*T, keeps the loss scale the same no matter how much padding a batch has. Deep learning libraries implement exactly this with an ignore_index argument.

Shapes and data flow
logits (B, T, V) -> (B*T, V); targets (B*T,); valid mask (B*T,); dlogits (B, T, V)
Topics
Evaluation metrics
Companies1
  • OpenAI a candidate reported this question AI interviews stopped asking 'what is a transformer'; now they hand you a broken one (Medium)

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

Similar questions
  • Build a precision recall curve and average precision with tied scoresHard
  • Compute sentence BLEU with brevity penaltyHard
  • Score multiple-choice answers by log-likelihoodHard
  • Evaluate perplexity of a long text with a strided sliding windowHard
All Evaluation metrics problems
Report
175 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def lm_cross_entropy(logits, targets, ignore=-100):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

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