Skip to content
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

Improve OptimizerWrapper composability #85

Merged
merged 5 commits into from
Jan 30, 2025
Merged
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
11 changes: 10 additions & 1 deletion torchft/optim.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@

"""

from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional

import torch
from torch.optim import Optimizer

if TYPE_CHECKING:
Expand Down Expand Up @@ -52,3 +53,11 @@ def step(self, closure: Optional[object] = None) -> None:
assert closure is None, "optimizers that use closures are not supported"
if self.manager.should_commit():
self.optim.step()

@property
def param_groups(self) -> List[Dict[str, Any]]:
return self.optim.param_groups

@property
def state(self) -> Mapping[torch.Tensor, Any]: # pyre-fixme[3]
return self.optim.state
8 changes: 8 additions & 0 deletions torchft/optim_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from unittest import TestCase
from unittest.mock import MagicMock, create_autospec

import torch
from torch.nn import Linear
from torch.optim import AdamW

Expand Down Expand Up @@ -34,9 +35,16 @@ def test_optimizer_wrapper(self) -> None:
optim.zero_grad()
self.assertEqual(manager.start_quorum.call_count, 1)

b = torch.rand(3)
m(b).sum().backward()

manager.should_commit.return_value = True
optim.step()
manager.should_commit.return_value = False
optim.step()
self.assertEqual(len(optim.param_groups), 2)
self.assertEqual(optim.param_groups[1]["lr"], 1e-4)
self.assertEqual(optim.param_groups[1]["params"], [])
self.assertEqual(len(optim.state), len(list(m.parameters())))

self.assertEqual(manager.should_commit.call_count, 2)