KL Divergence Loss with Zero-Probability Targets

Quick Overview

Implement a row-wise log-softmax, a KL divergence loss with four reduction modes, and its gradient with respect to the logits in NumPy. Tests numerically stable log-space computation, handling of zero-probability target bins, input validation, and deriving the softmax gradient by hand.

KL Divergence Loss with Zero-Probability Targets

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three NumPy functions that together compute a KL divergence loss whose target distributions can contain zero-probability bins. - `log_softmax(logits)` returns the row-wise log-softmax of an `(n, k)` array. - `kl_divergence(target, log_pred, reduction="batchmean")` computes $\mathrm{KL}(p \,\|\, q) = \sum_j p_j (\ln p_j - \log q_j)$ for each row, where `target` holds $p$ and `log_pred` holds $\log q$. - `kl_divergence_grad_logits(target, logits)` returns the gradient of the `"batchmean"` loss of `log_softmax(logits)` with respect to `logits`. Requirements: - Bins where $p_j = 0$ contribute exactly 0, even when `log_pred` is `-inf` there. - Reductions: `"none"` returns shape `(n,)`, `"sum"` returns the total, `"batchmean"` returns the total divided by $n$, and `"mean"` returns the total divided by $n \cdot k$. - An unknown reduction, mismatched shapes, or non-2D inputs raise `ValueError`. - Results stay finite for logits of magnitude around 1000, and adding a per-row constant to the logits leaves both the loss and the gradient unchanged. - The gradient has the same shape as `logits`. Example: ```python p = [[0.0, 0.4, 0.6]] log_q = [[-np.inf, np.log(0.5), np.log(0.5)]] kl_divergence(p, log_q, "none") # -> [0.4*log(0.8) + 0.6*log(1.2)] ≈ [0.02014] ``` The first bin has zero target mass, so it adds nothing even though its log-prediction is `-inf`. The other two bins give `0.4 * ln(0.8) ≈ -0.08926` and `0.6 * ln(1.2) ≈ 0.10939`, which sum to about 0.02014. ```hint Stable log-softmax Think about which value you can subtract from every logit in a row without changing the softmax, and pick the one that keeps every exponential at most 1. ``` ```hint Zero-mass bins In floating point, `0.0 * -np.inf` is NaN. Decide which entries to compute before you multiply anything. ``` ```hint The gradient Only the cross-entropy part of the KL sum depends on the logits. Differentiate that part through log-softmax one entry at a time. ``` ### Constraints & Assumptions - Inputs are 2D array-likes of floats with shape `(n, k)`, and `target` must match `log_pred` (or `logits`) in shape. - Logits can have magnitude around 1000. - Target entries are probabilities, so they are nonnegative. - The gradient is computed analytically with NumPy. ### Clarifying Questions to Ask - Does every target row sum to 1, or can rows be unnormalized weights? - Should `kl_divergence_grad_logits` run the same shape and dimension checks as `kl_divergence`? - When $p_j > 0$ and `log_pred` is `-inf`, should the loss return `inf` or raise? ### What a Strong Answer Covers - A numerically stable log-softmax that stays finite at magnitude 1000 and is invariant to per-row constants. - Handling of zero-mass bins that yields exactly 0 with no NaN or warnings, including where `log_pred` is `-inf`. - All four reductions with the correct divisors, and `ValueError` for bad reductions, shapes and dimensions. - A derivation of the gradient through log-softmax and code that matches it, with the output shaped like `logits`. - A check of the results against the example and a numerical gradient check. ### Follow-up Questions - Why does the gradient reduce to $(q - p)/n$, and when does that break? - What happens to the loss and to the gradient when a bin with positive target mass gets a predicted probability that underflows to 0? - How does this loss relate to cross-entropy with soft targets, and what differs between the two during training? - How would you check the analytic gradient numerically, and what step size would you choose?

Overview: Implement a row-wise log-softmax, a KL divergence loss with four reduction modes, and its gradient with respect to the logits in NumPy. Tests numerically stable log-space computation, handling of zero-probability target bins, input validation, and deriving the softmax gradient by hand.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three NumPy functions that together compute a KL divergence loss whose target distributions can contain zero-probability bins.

  • log_softmax(logits) returns the row-wise log-softmax of an (n, k) array.
  • kl_divergence(target, log_pred, reduction="batchmean") computes KL(p ∥ q)=∑jpj(ln⁡pj−log⁡qj)\mathrm{KL}(p \,\|\, q) = \sum_j p_j (\ln p_j - \log q_j) for each row, where target holds pp and log_pred holds log⁡q\log q .
  • kl_divergence_grad_logits(target, logits) returns the gradient of the "batchmean" loss of log_softmax(logits) with respect to logits .

Requirements:

  • Bins where pj=0p_j = 0 contribute exactly 0, even when log_pred is -inf there.
  • Reductions: "none" returns shape (n,) , "sum" returns the total, "batchmean" returns the total divided by nn , and "mean" returns the total divided by n⋅kn \cdot k .
  • An unknown reduction, mismatched shapes, or non-2D inputs raise ValueError .
  • Results stay finite for logits of magnitude around 1000, and adding a per-row constant to the logits leaves both the loss and the gradient unchanged.
  • The gradient has the same shape as logits .

Example:

p = [[0.0, 0.4, 0.6]]
log_q = [[-np.inf, np.log(0.5), np.log(0.5)]]
kl_divergence(p, log_q, "none")
# -> [0.4*log(0.8) + 0.6*log(1.2)] ≈ [0.02014]

The first bin has zero target mass, so it adds nothing even though its log-prediction is -inf. The other two bins give 0.4 * ln(0.8) ≈ -0.08926 and 0.6 * ln(1.2) ≈ 0.10939, which sum to about 0.02014.

Constraints & Assumptions

  • Inputs are 2D array-likes of floats with shape (n, k) , and target must match log_pred (or logits ) in shape.
  • Logits can have magnitude around 1000.
  • Target entries are probabilities, so they are nonnegative.
  • The gradient is computed analytically with NumPy.

Clarifying Questions to Ask Guidance

  • Does every target row sum to 1, or can rows be unnormalized weights?
  • Should kl_divergence_grad_logits run the same shape and dimension checks as kl_divergence ?
  • When pj>0p_j > 0 and log_pred is -inf , should the loss return inf or raise?

What a Strong Answer Covers Guidance

  • A numerically stable log-softmax that stays finite at magnitude 1000 and is invariant to per-row constants.
  • Handling of zero-mass bins that yields exactly 0 with no NaN or warnings, including where log_pred is -inf .
  • All four reductions with the correct divisors, and ValueError for bad reductions, shapes and dimensions.
  • A derivation of the gradient through log-softmax and code that matches it, with the output shaped like logits .
  • A check of the results against the example and a numerical gradient check.

Follow-up Questions Guidance

  • Why does the gradient reduce to (q−p)/n(q - p)/n , and when does that break?
  • What happens to the loss and to the gradient when a bin with positive target mass gets a predicted probability that underflows to 0?
  • How does this loss relate to cross-entropy with soft targets, and what differs between the two during training?
  • How would you check the analytic gradient numerically, and what step size would you choose?