What loss-formulation issues commonly cause a model's loss to become NaN?

Quick Overview

Asks which ways of writing a loss function make training produce NaN values. Tests numerical stability of the loss in both the forward and backward pass, how to rewrite a loss so it stays finite, and how to find the operation that produced the first NaN.

What loss-formulation issues commonly cause a model's loss to become NaN?

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

What loss-formulation issues commonly cause a model's loss to become NaN? ```hint Look for restricted domains Go through each operation in the loss that has a restricted domain or can overflow, and ask which inputs push it to the edge. ``` ```hint Forward and backward A loss can be finite in the forward pass while its gradient is not. Check where a derivative becomes infinite and what it gets multiplied by. ``` ### What a Strong Answer Covers - Operations inside the loss that are undefined for some inputs, and the inputs that trigger them - How infinities turn into NaN, in the forward pass or in the gradient - Sources of overflow and instability during training, including numeric precision - Bad data or labels as a separate source - Concrete fixes, and a way to locate the first NaN ### Follow-up Questions - Why does `torch.where(x > 0, torch.log(x), 0)` still produce NaN gradients? - Write a numerically stable binary cross-entropy on logits and explain why it cannot overflow. - Training runs fine for 10,000 steps and then the loss turns NaN. How do you debug it? - How does bf16 change the overflow picture compared with fp16?

Overview: Asks which ways of writing a loss function make training produce NaN values. Tests numerical stability of the loss in both the forward and backward pass, how to rewrite a loss so it stays finite, and how to find the operation that produced the first NaN.

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

What loss-formulation issues commonly cause a model's loss to become NaN?

What a Strong Answer Covers Guidance

  • Operations inside the loss that are undefined for some inputs, and the inputs that trigger them
  • How infinities turn into NaN, in the forward pass or in the gradient
  • Sources of overflow and instability during training, including numeric precision
  • Bad data or labels as a separate source
  • Concrete fixes, and a way to locate the first NaN

Follow-up Questions Guidance

  • Why does torch.where(x > 0, torch.log(x), 0) still produce NaN gradients?
  • Write a numerically stable binary cross-entropy on logits and explain why it cannot overflow.
  • Training runs fine for 10,000 steps and then the loss turns NaN. How do you debug it?
  • How does bf16 change the overflow picture compared with fp16?