Skip to content
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
25 changes: 25 additions & 0 deletions tests/unit/utilities/test_devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,3 +364,28 @@ def test_warn_if_mps_broken_warning_fires_only_once():
warn_if_mps(torch.device("mps"))
broken_warnings = [warning for warning in w if "known MPS bug" in str(warning.message)]
assert len(broken_warnings) == 1


def test_move_to_and_update_config_dtype_converts_params_without_rebuilding_state_dict():
"""Parameters are converted once by nn.Module.to(), not via repeated state_dict() calls."""
from types import SimpleNamespace

class CountingModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.cfg = SimpleNamespace(dtype=torch.float32, device="cpu")
self.layers = torch.nn.ModuleList(torch.nn.Linear(4, 4) for _ in range(5))
self.state_dict_calls = 0

def state_dict(self, *args, **kwargs):
self.state_dict_calls += 1
return super().state_dict(*args, **kwargs)

model = CountingModule()
result = move_to_and_update_config(model, torch.float16, print_details=False)

assert result is model
assert model.cfg.dtype == torch.float16
assert {p.dtype for p in model.parameters()} == {torch.float16}
# Previously this rebuilt the full state_dict once per parameter (quadratic cost).
assert model.state_dict_calls == 0
3 changes: 1 addition & 2 deletions transformer_lens/utilities/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,7 @@ def move_to_and_update_config(
model.cfg.dtype = device_or_dtype
if print_details:
print("Changing model dtype to", device_or_dtype)
for k, v in model.state_dict().items():
model.state_dict()[k] = v.to(device_or_dtype)
# The parameters themselves are converted by nn.Module.to() below.

# Call the base nn.Module.to() method to avoid recursion with custom to() methods
# Use the unbound method approach to avoid calling the overridden to() method
Expand Down
Loading