Skip to content

Fix SequentialLR deprecate warning about invoke step(epoch) #149392

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions test/optim/test_lrscheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,19 @@ def test_sequentiallr5(self):
scheduler = SequentialLR(self.opt, schedulers=schedulers, milestones=milestones)
self._test(scheduler, targets, epochs)

def test_sequentiallr_no_warnings(self):
scheduler1 = LinearLR(self.opt, start_factor=0.5, end_factor=0.1, total_iters=5)
scheduler2 = ExponentialLR(self.opt, gamma=0.9)
scheduler = SequentialLR(
self.opt, schedulers=[scheduler1, scheduler2], milestones=[5]
)

for _ in range(10):
self.opt.step()
with warnings.catch_warnings(record=True) as ws:
scheduler.step()
self.assertTrue(len(ws) == 0, "No warning should be raised")

def test_get_last_lr_sequentiallr(self):
epochs = 12
milestones = [3, 6]
Expand Down
7 changes: 5 additions & 2 deletions torch/optim/lr_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,13 +200,16 @@ def step(self, epoch: Optional[int] = None) -> None:
)

self._step_count += 1
if epoch is not None:
warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning)
self._update_lr(epoch)

def _update_lr(self, epoch: Optional[int] = None):
with _enable_get_lr_call(self):
if epoch is None:
self.last_epoch += 1
values = self.get_lr()
else:
warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning)
self.last_epoch = epoch
if hasattr(self, "_get_closed_form_lr"):
values = cast(list[float], self._get_closed_form_lr())
Expand Down Expand Up @@ -913,7 +916,7 @@ def step(self) -> None: # type: ignore[override]
idx = bisect_right(self._milestones, self.last_epoch)
scheduler = self._schedulers[idx]
if idx > 0 and self._milestones[idx - 1] == self.last_epoch:
scheduler.step(0)
scheduler._update_lr(0)
else:
scheduler.step()

Expand Down
Loading