-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add special logic for 'step' in _optimizer_to_device (#20019)
Co-authored-by: Adrian Wälchli <[email protected]>
- Loading branch information
Showing
4 changed files
with
88 additions
and
28 deletions.
There are no files selected for viewing
This file contains 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 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 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 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) |