From c931825e284f95d854813f6320af36c2c1e74fa6 Mon Sep 17 00:00:00 2001 From: MOHAMMED FAISAL PARVEZ Date: Wed, 25 Nov 2026 20:27:09 +0530 Subject: [PATCH] fix: drop no-op state_dict loop in move_to_and_update_config dtype branch The loop wrote into a fresh state_dict() copy, so it never changed the model; nn.Module.to() already converts the parameters. It rebuilt the state_dict once per parameter (quadratic) and discarded a cast of every tensor. Remove it and add a test. Co-Authored-By: Claude Opus 5.5 --- tests/unit/utilities/test_devices.py | 25 +++++++++++++++++++++++++ transformer_lens/utilities/devices.py | 3 +-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tests/unit/utilities/test_devices.py b/tests/unit/utilities/test_devices.py index 4cadfe3dc6..f4ab56764f 100644 --- a/tests/unit/utilities/test_devices.py +++ b/tests/unit/utilities/test_devices.py @@ -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 diff --git a/transformer_lens/utilities/devices.py b/transformer_lens/utilities/devices.py index a069d227d7..86d3dc943a 100644 --- a/transformer_lens/utilities/devices.py +++ b/transformer_lens/utilities/devices.py @@ -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