Skip to content

Reject NaN lr, momentum and weight_decay in SGD - #199953

Closed
G26karthik wants to merge 1 commit into
pytorch:mainfrom
G26karthik:fix/sgd-nan-hyperparameter-validation
Closed

G26karthik wants to merge 1 commit into
pytorch:mainfrom
G26karthik:fix/sgd-nan-hyperparameter-validation

Conversation

@G26karthik

@G26karthik G26karthik commented Oct 6, 2026 •

Copy link
Copy Markdown

Issue being fixed

Fixes #199516

BC-breaking?

No

Summary (human written only)

I noticed while comparing how the built-in optimizers validate their hyperparameters that SGD is the only one that accepts NaN for lr, momentum and weight_decay. SGD checks if lr < 0.0, which is False for NaN, while Adam, AdamW, RMSprop, Adagrad and the other built-in optimizers use if not 0.0 <= lr, which rejects it. The result is a silent NaN training run instead of an error at construction. This PR fixes that by using the same check in SGD.

Agent details (if applicable)

Prepared with Claude Code (AI assistant) and reviewed by me:

SGD.__init__ validated lr, momentum and weight_decay with x < 0.0. Ordered comparisons with NaN are False, so NaN passed all three checks and made the parameters NaN during step(). The checks now use not 0.0 <= x, the idiom the other built-in optimizers (Adam, AdamW, RMSprop, Adagrad, ...) already use, so NaN raises the same ValueError at construction with the existing messages. Valid and negative values behave exactly as before. The shared idiom is used rather than separate math.isnan checks so SGD stays consistent with the rest of torch.optim. Adds NaN cases for all three arguments to optim_error_inputs_func_sgd.

Tested on nightly 2.15.0.dev20261001+cpu (Windows, CPU only); both changed files are identical on current main and in that nightly. test_errors_SGD_cpu_float32 fails without the fix (the NaN lr gets past validation and construction raises TypeError instead of ValueError) and passes with it. All 129 tests matching SGD pass (27 skipped, CUDA-only). Lint: the RUFF and PYFMT lintrunner adapters report no issues on the changed files.

python test/test_optim.py -k test_errors_SGD
python test/test_optim.py -k SGD

SGD validated these with `x < 0.0`, which is False for NaN, so a NaN
value was accepted and turned the parameters into NaN during step().
Use `not 0.0 <= x`, as the other built-in optimizers already do, so NaN
raises the same ValueError at construction.

Fixes pytorch#199516
@pytorch-bot

pytorch-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

SGD.__init__ now uses `not 0.0 <= x` for lr/momentum/weight_decay, so NaN is
rejected, matching every sibling optimizer (Adam, RMSprop, Adagrad, etc.). The
three new ErrorOptimizerInput entries are genuine regression tests: under the
old `< 0.0` checks they would surface a TypeError from params=None rather than
the expected ValueError. No correctness, BC, or test-adequacy problems found.

Reviewed commit: 5a5e00b

Review run

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199953

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 5a5e00b with merge base 921d395 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: G26karthik / name: G26Karthik (5a5e00b)

@G26karthik
G26karthik marked this pull request as ready for review October 6, 2026 19:15
Copilot AI balanced review requested due to automatic review settings October 6, 2026 19:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 6, 2026
@janeyx99

janeyx99 commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot pre-review accept

@janeyx99 janeyx99 added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 7, 2026
Comment thread torch/optim/sgd.py Resolved
@github-actions github-actions Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 7, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review of 5a5e00b: nothing blocking; ready for human review.

SGD.init now uses not 0.0 &lt;= x for lr/momentum/weight_decay, so NaN is rejected, matching every sibling optimizer (Adam, RMSprop, Adagrad, etc.). The three new ErrorOptimizerInput entries are genuine regression tests: under the old &lt; 0.0 checks they would surface a TypeError from params=None rather than the expected ValueError. No correctness, BC, or test-adequacy problems found.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@janeyx99 janeyx99 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh i was silly and didn't notice u inverted the operands

@janeyx99

janeyx99 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 7, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Comment with id 6048096084 not found

Details for Dev Infra team Raised by workflow job

@janeyx99

janeyx99 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
## Issue being fixed

Fixes pytorch#199516

## BC-breaking?

No

## Summary (human written only)

I noticed while comparing how the built-in optimizers validate their hyperparameters that SGD is the only one that accepts NaN for `lr`, `momentum` and `weight_decay`. SGD checks `if lr < 0.0`, which is False for NaN, while Adam, AdamW, RMSprop, Adagrad and the other built-in optimizers use `if not 0.0 <= lr`, which rejects it. The result is a silent NaN training run instead of an error at construction. This PR fixes that by using the same check in SGD.

## Agent details (if applicable)

> Prepared with Claude Code (AI assistant) and reviewed by me:
>
> `SGD.__init__` validated `lr`, `momentum` and `weight_decay` with `x < 0.0`. Ordered comparisons with NaN are `False`, so NaN passed all three checks and made the parameters NaN during `step()`. The checks now use `not 0.0 <= x`, the idiom the other built-in optimizers (Adam, AdamW, RMSprop, Adagrad, ...) already use, so NaN raises the same `ValueError` at construction with the existing messages. Valid and negative values behave exactly as before. The shared idiom is used rather than separate `math.isnan` checks so SGD stays consistent with the rest of `torch.optim`. Adds NaN cases for all three arguments to `optim_error_inputs_func_sgd`.
>
> Tested on nightly 2.15.0.dev20261001+cpu (Windows, CPU only); both changed files are identical on current main and in that nightly. `test_errors_SGD_cpu_float32` fails without the fix (the NaN `lr` gets past validation and construction raises `TypeError` instead of `ValueError`) and passes with it. All 129 tests matching `SGD` pass (27 skipped, CUDA-only). Lint: the RUFF and PYFMT lintrunner adapters report no issues on the changed files.
>
> ```bash
> python test/test_optim.py -k test_errors_SGD
> python test/test_optim.py -k SGD
> ```

Pull Request resolved: pytorch#199953
Approved by: https://github.com/janeyx99

This branch was previously deployed

1 inactive deployment
bedrock — 5a5e00bb Deployed Oct 6, 2026 by pytorchbot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request Merged open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: optim triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

torch.optim.SGD accepts NaN lr, momentum and weight_decay; other optimizers raise ValueError

5 participants