-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Add special logic for 'step' in _optimizer_to_device #20019
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
aa0ec04
Add special logic for 'step' in _optimizer_to_device
corwinjoy fb4cf05
add tests
awaelchli 585fd43
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4ad418a
move note to the condition
awaelchli bec392b
Merge branch 'master' into optimizer_to_device
awaelchli 192ecce
update changelog
awaelchli 75f7783
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ef53040
Merge branch 'master' into optimizer_to_device
awaelchli 7d13190
update
awaelchli 8bacec9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 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 |
---|---|---|
@@ -1,36 +1,86 @@ | ||
import collections | ||
import dataclasses | ||
|
||
import pytest | ||
import torch | ||
from lightning.fabric.utilities.optimizer import _optimizer_to_device | ||
from torch import Tensor | ||
|
||
from tests_fabric.helpers.runif import RunIf | ||
|
||
def test_optimizer_to_device(): | ||
@dataclasses.dataclass(frozen=True) | ||
|
||
@pytest.mark.parametrize( | ||
"optimizer_class", | ||
[ | ||
torch.optim.Adam, | ||
torch.optim.AdamW, | ||
torch.optim.SGD, | ||
torch.optim.RMSprop, | ||
torch.optim.Adagrad, | ||
torch.optim.Adadelta, | ||
torch.optim.Adamax, | ||
], | ||
) | ||
@pytest.mark.parametrize( | ||
"src_device", | ||
[ | ||
torch.device("cpu"), | ||
pytest.param(torch.device("cuda"), marks=RunIf(min_cuda_gpus=1)), | ||
], | ||
) | ||
@pytest.mark.parametrize( | ||
"dst_device", | ||
[ | ||
torch.device("cpu"), | ||
pytest.param(torch.device("cuda"), marks=RunIf(min_cuda_gpus=1)), | ||
], | ||
) | ||
def test_optimizer_to_device(optimizer_class, src_device, dst_device): | ||
# Optimizer with no state initialized | ||
model = torch.nn.Linear(2, 2, device=src_device) | ||
optimizer = optimizer_class(model.parameters(), lr=0.1) | ||
_optimizer_to_device(optimizer, dst_device) | ||
_assert_opt_parameters_on_device(optimizer, dst_device) | ||
|
||
# Optimizer with state initialized | ||
model = torch.nn.Linear(2, 2, device=src_device) | ||
optimizer = optimizer_class(model.parameters(), lr=0.1) | ||
model(torch.randn(2, 2, device=src_device)).sum().backward() | ||
optimizer.step() | ||
_optimizer_to_device(optimizer, dst_device) | ||
_assert_opt_parameters_on_device(optimizer, dst_device) | ||
|
||
|
||
def _assert_opt_parameters_on_device(opt, device): | ||
for _, v in opt.state.items(): | ||
for key, item in v.items(): | ||
if not isinstance(item, Tensor): | ||
continue | ||
if key == "step": | ||
# The "step" tensor needs to remain on CPU | ||
assert item.device.type == "cpu" | ||
else: | ||
assert item.device.type == device.type | ||
|
||
|
||
@RunIf(min_cuda_gpus=1) | ||
@pytest.mark.parametrize("frozen", [True, False]) | ||
def test_optimizer_to_device_with_dataclass_in_state(frozen): | ||
src_device = torch.device("cpu") | ||
dst_device = torch.device("cuda") | ||
model = torch.nn.Linear(32, 2, device=src_device) | ||
|
||
@dataclasses.dataclass(frozen=frozen) | ||
class FooState: | ||
bar: int | ||
integer: int | ||
tensor: Tensor | ||
|
||
class TestOptimizer(torch.optim.SGD): | ||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.state["dummy"] = torch.tensor(0) | ||
self.state["frozen"] = FooState(0) | ||
|
||
layer = torch.nn.Linear(32, 2) | ||
opt = TestOptimizer(layer.parameters(), lr=0.1) | ||
_optimizer_to_device(opt, "cpu") | ||
if torch.cuda.is_available(): | ||
_optimizer_to_device(opt, "cuda") | ||
assert_opt_parameters_on_device(opt, "cuda") | ||
|
||
|
||
def assert_opt_parameters_on_device(opt, device: str): | ||
for param in opt.state.values(): | ||
# Not sure there are any global tensors in the state dict | ||
if isinstance(param, Tensor): | ||
assert param.data.device.type == device | ||
elif isinstance(param, collections.abc.Mapping): | ||
for subparam in param.values(): | ||
if isinstance(subparam, Tensor): | ||
assert param.data.device.type == device | ||
self.state[model.weight] = {"dummy": torch.tensor(0)} | ||
self.state[model.bias] = FooState(0, torch.tensor(0)) | ||
|
||
optimizer = TestOptimizer(model.parameters(), lr=0.1) | ||
_optimizer_to_device(optimizer, dst_device) | ||
assert optimizer.state[model.weight]["dummy"].device.type == dst_device.type | ||
assert optimizer.state[model.bias].tensor.device.type == ("cpu" if frozen else dst_device.type) |
Oops, something went wrong.
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.