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

Fix monkeypatching of _FabricModule methods #19705

Merged
merged 5 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion src/lightning/fabric/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).

- Fixed an issue causing a TypeError when using `torch.compile` as a decorator ([#19627](https://github.com/Lightning-AI/pytorch-lightning/pull/19627))

-
- Fixed issue where some model methods couldn't be monkeypatched after being Fabric wrapped ([#19705](https://github.com/Lightning-AI/pytorch-lightning/pull/19705))

-

Expand Down
2 changes: 1 addition & 1 deletion src/lightning/fabric/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def __setattr__(self, name: str, value: Any) -> None:
original_has_attr = hasattr(original_module, name)
# Can't use super().__getattr__ because nn.Module only checks _parameters, _buffers, and _modules
# Can't use self.__getattr__ because it would pass through to the original module
fabric_has_attr = name in self.__dict__
fabric_has_attr = hasattr(self, name)
carmocca marked this conversation as resolved.
Show resolved Hide resolved

if not (original_has_attr or fabric_has_attr):
setattr(original_module, name, value)
Expand Down
7 changes: 7 additions & 0 deletions tests/tests_fabric/test_wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,13 @@ def __init__(self):
assert linear in fabric_module.modules()
assert linear in original_module.modules()

# Check monkeypatching of methods
model = _FabricModule(Mock(), Mock())
assert isinstance(model, _FabricModule)
original = id(model.forward)
model.forward = lambda *_: None
assert id(model.forward) != original


def test_fabric_module_state_dict_access():
"""Test that state_dict access passes through to the original module."""
Expand Down
Loading