-
Couldn't load subscription status.
- Fork 575
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 3 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,54 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Utilities for detecting NaN values in loss during training.""" | ||
|
|
||
| import logging | ||
| import math | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class LossNaNError(RuntimeError): | ||
| """Exception raised when NaN is detected in total loss during training.""" | ||
|
|
||
| def __init__(self, step: int, total_loss: float) -> None: | ||
| """Initialize the exception. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| step : int | ||
| The training step where NaN was detected | ||
| total_loss : float | ||
| The total loss value that contains NaN | ||
| """ | ||
| self.step = step | ||
| self.total_loss = total_loss | ||
| message = ( | ||
| f"NaN detected in total loss at training step {step}: {total_loss}. " | ||
| f"Training stopped to prevent wasting time with corrupted parameters. " | ||
| f"This typically indicates unstable training conditions such as " | ||
| f"learning rate too high, poor data quality, or numerical instability." | ||
| ) | ||
| super().__init__(message) | ||
|
|
||
|
|
||
| def check_total_loss_nan(step: int, total_loss: float) -> None: | ||
| """Check if the total loss contains NaN and raise an exception if found. | ||
|
|
||
| This function is designed to be called during training after the total loss | ||
| is computed and converted to a CPU float value. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| step : int | ||
| Current training step | ||
| total_loss : float | ||
| Total loss value to check for NaN | ||
|
|
||
| Raises | ||
| ------ | ||
| LossNaNError | ||
| If the total loss contains NaN | ||
| """ | ||
| if math.isnan(total_loss): | ||
| log.error(f"NaN detected in total loss at step {step}: {total_loss}") | ||
| raise LossNaNError(step, total_loss) |
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,103 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Test cases for NaN detection utility.""" | ||
|
|
||
| import math | ||
| import unittest | ||
|
|
||
| import numpy as np | ||
|
|
||
| from deepmd.utils.nan_detector import ( | ||
| LossNaNError, | ||
| check_total_loss_nan, | ||
| ) | ||
|
|
||
|
|
||
| class TestNaNDetector(unittest.TestCase): | ||
| """Test the NaN detection utility functions.""" | ||
|
|
||
| def test_normal_values_pass(self): | ||
| """Test that normal loss values don't trigger NaN detection.""" | ||
| # Test with various normal values | ||
| normal_losses = [0.5, 1.0, 0.001, 0.0, -0.5] | ||
|
|
||
| # Should not raise any exception | ||
| for i, loss_val in enumerate(normal_losses): | ||
| try: | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| check_total_loss_nan(100 + i, loss_val) | ||
| except Exception as e: | ||
| self.fail(f"Normal values should not raise exception: {e}") | ||
|
|
||
| def test_nan_detection_raises_exception(self): | ||
| """Test that NaN values trigger the proper exception.""" | ||
| # Test with NaN value | ||
| with self.assertRaises(LossNaNError) as context: | ||
| check_total_loss_nan(200, float("nan")) | ||
|
|
||
| exception = context.exception | ||
| self.assertEqual(exception.step, 200) | ||
| self.assertTrue(math.isnan(exception.total_loss)) | ||
| self.assertIn("NaN detected in total loss at training step 200", str(exception)) | ||
|
|
||
| def test_various_nan_representations(self): | ||
| """Test detection of various NaN representations.""" | ||
| nan_values = [ | ||
| float("nan"), | ||
| np.nan, | ||
| math.nan, | ||
| ] | ||
|
|
||
| for i, nan_val in enumerate(nan_values): | ||
| with self.assertRaises(LossNaNError): | ||
| check_total_loss_nan(i, nan_val) | ||
|
|
||
| def test_error_message_format(self): | ||
| """Test that error messages contain useful information.""" | ||
| with self.assertRaises(LossNaNError) as context: | ||
| check_total_loss_nan(123, float("nan")) | ||
|
|
||
| error_msg = str(context.exception) | ||
|
|
||
| # Check key information is in the message | ||
| self.assertIn("step 123", error_msg) | ||
| self.assertIn("Training stopped", error_msg) | ||
| self.assertIn("learning rate too high", error_msg) | ||
|
|
||
| def test_edge_cases(self): | ||
| """Test edge cases for NaN detection.""" | ||
| # Infinity should not trigger NaN detection (separate issue) | ||
| try: | ||
| check_total_loss_nan(1, float("inf")) | ||
| check_total_loss_nan(2, float("-inf")) | ||
| except Exception as e: | ||
| self.fail(f"Infinity should not raise NaN exception: {e}") | ||
|
|
||
| def test_numeric_types(self): | ||
| """Test that various numeric types work correctly.""" | ||
| # Various numeric types that should pass | ||
| test_values = [ | ||
| 0.5, # float | ||
| 1, # int | ||
| np.float32(0.3), # NumPy float32 | ||
| np.float64(0.7), # NumPy float64 | ||
| ] | ||
|
|
||
| for i, val in enumerate(test_values): | ||
| try: | ||
| check_total_loss_nan(10 + i, float(val)) | ||
| except Exception as e: | ||
| self.fail(f"Numeric type {type(val)} should not raise exception: {e}") | ||
|
|
||
| def test_inheritance_from_runtime_error(self): | ||
| """Test that LossNaNError inherits from RuntimeError.""" | ||
| self.assertTrue(issubclass(LossNaNError, RuntimeError)) | ||
|
|
||
| try: | ||
| check_total_loss_nan(999, float("nan")) | ||
| except LossNaNError as e: | ||
| self.assertIsInstance(e, RuntimeError) | ||
| except Exception: | ||
| self.fail("Should raise LossNaNError which inherits from RuntimeError") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
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,102 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Integration test to verify NaN detection during training. | ||
| This test creates a mock training scenario where total loss becomes NaN | ||
| and verifies that the training stops with appropriate error message. | ||
| """ | ||
|
|
||
| import unittest | ||
| from unittest.mock import ( | ||
| patch, | ||
| ) | ||
|
|
||
| from deepmd.utils.nan_detector import ( | ||
| LossNaNError, | ||
| check_total_loss_nan, | ||
| ) | ||
|
|
||
|
|
||
| class TestNaNDetectionIntegration(unittest.TestCase): | ||
| """Integration tests for NaN detection during training.""" | ||
|
|
||
| def test_training_stops_on_nan_loss(self): | ||
| """Test that training stops when NaN is detected in total loss.""" | ||
| # Normal total loss should pass | ||
| try: | ||
| check_total_loss_nan(100, 0.1) | ||
| except Exception as e: | ||
| self.fail(f"Normal total loss should not raise exception: {e}") | ||
|
|
||
| # NaN total loss should raise | ||
| with self.assertRaises(LossNaNError) as context: | ||
| check_total_loss_nan(100, float("nan")) | ||
|
|
||
| exception = context.exception | ||
| self.assertEqual(exception.step, 100) | ||
| self.assertIn("NaN detected in total loss", str(exception)) | ||
|
|
||
| @patch("deepmd.utils.nan_detector.log") | ||
| def test_logging_on_nan_detection(self, mock_log): | ||
| """Test that NaN detection logs appropriate error messages.""" | ||
| with self.assertRaises(LossNaNError): | ||
| check_total_loss_nan(200, float("nan")) | ||
|
|
||
| # Verify that error was logged | ||
| mock_log.error.assert_called_once() | ||
| logged_message = mock_log.error.call_args[0][0] | ||
| self.assertIn("NaN detected in total loss at step 200", logged_message) | ||
|
|
||
| def test_training_simulation_with_checkpoint_prevention(self): | ||
| """Simulate the training checkpoint scenario to ensure NaN prevents saving.""" | ||
|
|
||
| def mock_save_checkpoint(): | ||
| """Mock function that should not be called when NaN is detected.""" | ||
| raise AssertionError("Checkpoint should not be saved when NaN is detected!") | ||
|
|
||
| # Simulate the training flow: check total loss, then save checkpoint | ||
| step_id = 1000 | ||
| total_loss = float("nan") | ||
|
|
||
| # This should raise LossNaNError before checkpoint saving | ||
| with self.assertRaises(LossNaNError): | ||
| check_total_loss_nan(step_id, total_loss) | ||
| # This line should never be reached | ||
| mock_save_checkpoint() | ||
njzjz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # Verify the error contains expected information | ||
| try: | ||
| check_total_loss_nan(step_id, total_loss) | ||
| except LossNaNError as e: | ||
| self.assertIn("Training stopped to prevent wasting time", str(e)) | ||
| self.assertIn("corrupted parameters", str(e)) | ||
|
|
||
| def test_realistic_training_scenario(self): | ||
| """Test a more realistic training scenario with decreasing then NaN loss.""" | ||
| # Simulate normal training progression | ||
| normal_steps = [ | ||
| (1, 1.0), # Initial high loss | ||
| (10, 0.5), # Loss decreasing | ||
| (20, 0.25), # Loss continuing to decrease | ||
| (50, 0.1), # Good progress | ||
| ] | ||
|
|
||
| # All normal steps should pass | ||
| for step, loss_val in normal_steps: | ||
| try: | ||
| check_total_loss_nan(step, loss_val) | ||
| except Exception as e: | ||
| self.fail( | ||
| f"Normal training step {step} should not raise exception: {e}" | ||
| ) | ||
|
|
||
| # But when loss becomes NaN, training should stop | ||
| with self.assertRaises(LossNaNError) as context: | ||
| check_total_loss_nan(100, float("nan")) | ||
|
|
||
| exception = context.exception | ||
| self.assertEqual(exception.step, 100) | ||
| self.assertIn("Training stopped", str(exception)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
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.