|
| 1 | +From 52cc26db222976bbdf940ce110ad28bb5ea1cfc5 Mon Sep 17 00:00:00 2001 |
| 2 | +From: AllSpark <allspark@microsoft.com> |
| 3 | +Date: Thu, 29 Jan 2026 14:25:44 +0000 |
| 4 | +Subject: [PATCH] override SWALR.state_dict and load_state_dict (#163122) |
| 5 | + |
| 6 | +Fixes #163105 |
| 7 | + |
| 8 | +- Add typing_extensions.override |
| 9 | +- Use _set_anneal_func to set anneal function |
| 10 | +- Implement state_dict and load_state_dict for SWALR excluding optimizer and anneal_func |
| 11 | + |
| 12 | +Signed-off-by: Azure Linux Security Servicing Account <azurelinux-security@microsoft.com> |
| 13 | +Upstream-reference: AI Backport of https://github.com/pytorch/pytorch/commit/167ad09be5af5c52666759412a3804068c6955d1.patch |
| 14 | +--- |
| 15 | + test/test_optim.py | 16 ++++++++++++++++ |
| 16 | + torch/optim/swa_utils.py | 37 +++++++++++++++++++++++++++++++++---- |
| 17 | + 2 files changed, 49 insertions(+), 4 deletions(-) |
| 18 | + |
| 19 | +diff --git a/test/test_optim.py b/test/test_optim.py |
| 20 | +index 1608478b..d3dd4567 100644 |
| 21 | +--- a/test/test_optim.py |
| 22 | ++++ b/test/test_optim.py |
| 23 | +@@ -3968,6 +3968,22 @@ class TestLRScheduler(TestCase): |
| 24 | + |
| 25 | + self.assertLessEqual(last_lr, max_lr) |
| 26 | + |
| 27 | ++ @parametrize("LRClass", [partial(SWALR, swa_lr=0.01)]) |
| 28 | ++ @parametrize("weights_only", [True, False]) |
| 29 | ++ def test_lr_scheduler_state_dict_load(self, LRClass, weights_only): |
| 30 | ++ scheduler = LRClass(self.opt) |
| 31 | ++ state_dict = scheduler.state_dict() |
| 32 | ++ |
| 33 | ++ with tempfile.TemporaryFile() as f: |
| 34 | ++ torch.save(state_dict, f) |
| 35 | ++ f.seek(0) |
| 36 | ++ state_dict_loaded = torch.load(f, weights_only=weights_only) |
| 37 | ++ self.assertEqual(state_dict, state_dict_loaded) |
| 38 | ++ # Make sure state_dict can be loaded |
| 39 | ++ scheduler2 = LRClass(self.opt) |
| 40 | ++ scheduler2.load_state_dict(state_dict_loaded) |
| 41 | ++ self.assertEqual(scheduler2.state_dict(), state_dict) |
| 42 | ++ |
| 43 | + |
| 44 | + class SWATestDNN(torch.nn.Module): |
| 45 | + def __init__(self, input_features): |
| 46 | +diff --git a/torch/optim/swa_utils.py b/torch/optim/swa_utils.py |
| 47 | +index dda4b8ad..d18084e2 100644 |
| 48 | +--- a/torch/optim/swa_utils.py |
| 49 | ++++ b/torch/optim/swa_utils.py |
| 50 | +@@ -2,6 +2,7 @@ import itertools |
| 51 | + import math |
| 52 | + from copy import deepcopy |
| 53 | + import warnings |
| 54 | ++from typing_extensions import override |
| 55 | + |
| 56 | + import torch |
| 57 | + from torch.nn import Module |
| 58 | +@@ -247,10 +248,7 @@ class SWALR(LRScheduler): |
| 59 | + if anneal_strategy not in ['cos', 'linear']: |
| 60 | + raise ValueError("anneal_strategy must by one of 'cos' or 'linear', " |
| 61 | + f"instead got {anneal_strategy}") |
| 62 | +- elif anneal_strategy == 'cos': |
| 63 | +- self.anneal_func = self._cosine_anneal |
| 64 | +- elif anneal_strategy == 'linear': |
| 65 | +- self.anneal_func = self._linear_anneal |
| 66 | ++ self._set_anneal_func(anneal_strategy) |
| 67 | + if not isinstance(anneal_epochs, int) or anneal_epochs < 0: |
| 68 | + raise ValueError(f"anneal_epochs must be equal or greater than 0, got {anneal_epochs}") |
| 69 | + self.anneal_epochs = anneal_epochs |
| 70 | +@@ -296,3 +294,34 @@ class SWALR(LRScheduler): |
| 71 | + alpha = self.anneal_func(t) |
| 72 | + return [group['swa_lr'] * alpha + lr * (1 - alpha) |
| 73 | + for group, lr in zip(self.optimizer.param_groups, prev_lrs)] |
| 74 | ++ |
| 75 | ++ def _set_anneal_func(self, anneal_strategy: Literal["cos", "linear"]): |
| 76 | ++ self._anneal_strategy = anneal_strategy |
| 77 | ++ if anneal_strategy == "cos": |
| 78 | ++ self.anneal_func = self._cosine_anneal |
| 79 | ++ else: |
| 80 | ++ self.anneal_func = self._linear_anneal |
| 81 | ++ |
| 82 | ++ @override |
| 83 | ++ def state_dict(self) -> dict[str, Any]: |
| 84 | ++ """Return the state of the scheduler as a :class:`dict`. |
| 85 | ++ |
| 86 | ++ It contains an entry for every variable in self.__dict__ which |
| 87 | ++ is not the optimizer or anneal_func. |
| 88 | ++ """ |
| 89 | ++ return { |
| 90 | ++ key: value |
| 91 | ++ for key, value in self.__dict__.items() |
| 92 | ++ if key not in ("optimizer", "anneal_func") |
| 93 | ++ } |
| 94 | ++ |
| 95 | ++ @override |
| 96 | ++ def load_state_dict(self, state_dict: dict[str, Any]) -> None: |
| 97 | ++ """Load the scheduler's state. |
| 98 | ++ |
| 99 | ++ Args: |
| 100 | ++ state_dict (dict): scheduler state. Should be an object returned |
| 101 | ++ from a call to :meth:`state_dict`. |
| 102 | ++ """ |
| 103 | ++ self.__dict__.update(state_dict) |
| 104 | ++ self._set_anneal_func(self._anneal_strategy) |
| 105 | +-- |
| 106 | +2.45.4 |
| 107 | + |
0 commit comments