Guarded BCE Loss with Clipping and NaN Detection

Quick Overview

Implement a numerically stable binary cross-entropy from logits in NumPy, a guarded loss that clips large values and drops NaN or infinite ones, and its analytic gradient. Tests stable log-sum-exp style formulas, masking with weights, and gradient correctness at the clip boundary.

Guarded BCE Loss with Clipping and NaN Detection

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three NumPy functions: a numerically stable per-sample BCE from logits, a guarded aggregate loss that clips and drops non-finite values, and its analytic gradient with respect to the logits. Inputs may be any array shape and are flattened to 1-D. ```python def bce_with_logits_per_sample(y, logits): ... def guarded_loss(per_sample_losses, clip_value, scale, sample_weight=None): ... def guarded_bce_grad_logits(y, logits, clip_value, scale, sample_weight=None): ... ``` The functions must behave as follows: - `bce_with_logits_per_sample(y, logits)` returns a 1-D array that stays finite for logits like `±1000`. - `guarded_loss` returns `(loss: float, n_clipped: int, n_nonfinite: int)` as Python types. NaN and ±Inf losses are counted and excluded from both the numerator and the denominator. - Finite losses `> clip_value` are clipped and counted. `loss = scale * Σ w·min(l, clip) / Σ w` over finite samples. `sample_weight=None` means all ones. - `guarded_bce_grad_logits` returns `scale * w * (sigmoid(z) - y) / Σ w_finite` for samples whose loss is finite and `≤ clip_value`. All other entries are `0.0`, and the output is always finite. - If the finite weight sum is `≤ 0`, the loss is `0.0` (counts are still reported) and the gradient is all zeros. For example: ```python guarded_loss([0.5, 3.0, 1.0, 10.0], clip_value=2.0, scale=4.0) # -> (5.5, 2, 0) # 4 * (0.5 + 2 + 1 + 2) / 4 guarded_bce_grad_logits([1, 0, 1, 0], [np.nan, 50.0, 0.0, np.inf], clip_value=5.0, scale=2.0) # -> [0.0, 0.0, -0.5, 0.0] # NaN/Inf losses dropped, loss 50 clipped ``` ```hint Stable BCE Start from log(1 + e^z) - y·z and split the first term so the exponential only ever sees a non-positive argument. ``` ```hint Which samples move the loss Ask which samples change the loss when z moves slightly, and check what a 0/1 mask does when it multiplies a NaN. ``` ### Constraints & Assumptions - `y`, `logits`, `per_sample_losses` and `sample_weight` may have any shape and are flattened to 1-D. - Logits can be as large as `±1000` and may contain NaN or ±Inf. - `sample_weight` is either `None` or one weight per sample. ### What a Strong Answer Covers - A BCE-from-logits form that cannot overflow, with a short derivation. - Masking that removes non-finite samples from both sums while keeping clipped samples in the denominator, and counts returned as Python types. - A gradient that is zero for clipped and non-finite samples, matches finite differences for active ones, and is never NaN. - The case where the finite weight sum is zero or negative. - Time and space cost. ### Follow-up Questions - Clipped samples get a zero gradient. What does that do to training on hard or mislabeled examples, and what is a softer alternative? - Why keep clipped samples in the denominator? What changes if you drop them? - How should a training loop react when `n_nonfinite` is not zero?

Overview: Implement a numerically stable binary cross-entropy from logits in NumPy, a guarded loss that clips large values and drops NaN or infinite ones, and its analytic gradient. Tests stable log-sum-exp style formulas, masking with weights, and gradient correctness at the clip boundary.

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

Implement three NumPy functions: a numerically stable per-sample BCE from logits, a guarded aggregate loss that clips and drops non-finite values, and its analytic gradient with respect to the logits. Inputs may be any array shape and are flattened to 1-D.

def bce_with_logits_per_sample(y, logits): ...
def guarded_loss(per_sample_losses, clip_value, scale, sample_weight=None): ...
def guarded_bce_grad_logits(y, logits, clip_value, scale, sample_weight=None): ...

The functions must behave as follows:

  • bce_with_logits_per_sample(y, logits) returns a 1-D array that stays finite for logits like ±1000 .
  • guarded_loss returns (loss: float, n_clipped: int, n_nonfinite: int) as Python types. NaN and ±Inf losses are counted and excluded from both the numerator and the denominator.
  • Finite losses > clip_value are clipped and counted. loss = scale * Σ w·min(l, clip) / Σ w over finite samples. sample_weight=None means all ones.
  • guarded_bce_grad_logits returns scale * w * (sigmoid(z) - y) / Σ w_finite for samples whose loss is finite and ≤ clip_value . All other entries are 0.0 , and the output is always finite.
  • If the finite weight sum is ≤ 0 , the loss is 0.0 (counts are still reported) and the gradient is all zeros.

For example:

guarded_loss([0.5, 3.0, 1.0, 10.0], clip_value=2.0, scale=4.0)
# -> (5.5, 2, 0)   # 4 * (0.5 + 2 + 1 + 2) / 4

guarded_bce_grad_logits([1, 0, 1, 0], [np.nan, 50.0, 0.0, np.inf], clip_value=5.0, scale=2.0)
# -> [0.0, 0.0, -0.5, 0.0]   # NaN/Inf losses dropped, loss 50 clipped

Constraints & Assumptions

  • y , logits , per_sample_losses and sample_weight may have any shape and are flattened to 1-D.
  • Logits can be as large as ±1000 and may contain NaN or ±Inf.
  • sample_weight is either None or one weight per sample.

What a Strong Answer Covers Guidance

  • A BCE-from-logits form that cannot overflow, with a short derivation.
  • Masking that removes non-finite samples from both sums while keeping clipped samples in the denominator, and counts returned as Python types.
  • A gradient that is zero for clipped and non-finite samples, matches finite differences for active ones, and is never NaN.
  • The case where the finite weight sum is zero or negative.
  • Time and space cost.

Follow-up Questions Guidance

  • Clipped samples get a zero gradient. What does that do to training on hard or mislabeled examples, and what is a softer alternative?
  • Why keep clipped samples in the denominator? What changes if you drop them?
  • How should a training loop react when n_nonfinite is not zero?