-
Notifications
You must be signed in to change notification settings - Fork 576
feat: add NaN detection during training #4986
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
7
commits into
devel
Choose a base branch
from
copilot/fix-4985
base: devel
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ef431a1
Initial plan
Copilot 9eb1bea
feat(training): add comprehensive NaN detection with tests and valida…
Copilot 5a22dfc
fix(training): address PR feedback - simplify NaN detection API and i…
Copilot 0852b7c
fix(training): optimize NaN detection based on feedback - use lcurve …
Copilot 7a2b41e
fix(training): use 'rmse' key for total loss instead of 'rmse_e' for …
Copilot 22cb9ef
fix: revert implib file and clean up redundant test code
Copilot 0bebb06
fix: properly revert implib file to exact original state
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Utilities for detecting NaN values in loss during training.""" | ||
|
|
||
| import logging | ||
| import math | ||
| from typing import ( | ||
| Any, | ||
| ) | ||
|
|
||
| import numpy as np | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class LossNaNError(Exception): | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Exception raised when NaN is detected in loss during training.""" | ||
|
|
||
| def __init__(self, step: int, loss_dict: dict[str, Any]) -> None: | ||
| """Initialize the exception. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| step : int | ||
| The training step where NaN was detected | ||
| loss_dict : dict[str, Any] | ||
| Dictionary containing the loss values where NaN was found | ||
| """ | ||
| self.step = step | ||
| self.loss_dict = loss_dict | ||
| super().__init__(self._format_message()) | ||
|
|
||
| def _format_message(self) -> str: | ||
| """Format the error message.""" | ||
| nan_losses = [] | ||
| for key, value in self.loss_dict.items(): | ||
| if self._is_nan(value): | ||
| nan_losses.append(f"{key}={value}") | ||
|
|
||
| message = ( | ||
| f"NaN detected in loss at training step {self.step}. " | ||
| f"Training stopped to prevent wasting time with corrupted parameters. " | ||
| f"NaN values found in: {', '.join(nan_losses)}. " | ||
| f"This typically indicates unstable training conditions such as " | ||
| f"learning rate too high, poor data quality, or numerical instability." | ||
| ) | ||
| return message | ||
|
|
||
| @staticmethod | ||
| def _is_nan(value: Any) -> bool: | ||
| """Check if a value is NaN.""" | ||
| if value is None: | ||
| return False | ||
| try: | ||
| # Handle various tensor types and Python scalars | ||
| if hasattr(value, "item"): | ||
| # PyTorch/TensorFlow/PaddlePaddle tensor | ||
| return math.isnan(value.item()) | ||
| elif isinstance(value, (int, float)): | ||
| # Python scalar | ||
| return math.isnan(value) | ||
| elif isinstance(value, np.ndarray): | ||
| # NumPy array | ||
| return np.isnan(value).any() | ||
| else: | ||
| # Try to convert to float and check | ||
| return math.isnan(float(value)) | ||
| except (TypeError, ValueError): | ||
| # If we can't convert to float, assume it's not NaN | ||
| return False | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def check_loss_nan(step: int, loss_dict: dict[str, Any]) -> None: | ||
| """Check if any loss values contain NaN and raise an exception if found. | ||
|
|
||
| This function is designed to be called during training after loss values | ||
| are computed and available on CPU, typically during the logging/display phase. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| step : int | ||
| Current training step | ||
| loss_dict : dict[str, Any] | ||
| Dictionary containing loss values to check for NaN | ||
|
|
||
| Raises | ||
| ------ | ||
| LossNaNError | ||
| If any loss value contains NaN | ||
| """ | ||
| nan_found = False | ||
| for key, value in loss_dict.items(): | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if LossNaNError._is_nan(value): | ||
| nan_found = True | ||
| log.error(f"NaN detected in {key} at step {step}: {value}") | ||
|
|
||
| if nan_found: | ||
| raise LossNaNError(step, loss_dict) | ||
|
|
||
|
|
||
| def check_single_loss_nan(step: int, loss_name: str, loss_value: Any) -> None: | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Check if a single loss value contains NaN and raise an exception if found. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| step : int | ||
| Current training step | ||
| loss_name : str | ||
| Name/identifier of the loss | ||
| loss_value : Any | ||
| Loss value to check for NaN | ||
|
|
||
| Raises | ||
| ------ | ||
| LossNaNError | ||
| If the loss value contains NaN | ||
| """ | ||
| if LossNaNError._is_nan(loss_value): | ||
| log.error(f"NaN detected in {loss_name} at step {step}: {loss_value}") | ||
| raise LossNaNError(step, {loss_name: loss_value}) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.