Skip to content

Commit 02fa32b

Browse files
authored
Handle torch.jit scripted modules in layer summary (#6511)
1 parent 0544efd commit 02fa32b

File tree

3 files changed

+34
-5
lines changed

3 files changed

+34
-5
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
140140
- Fixed LightningModule `all_gather` on cpu tensors ([#6416](https://github.com/PyTorchLightning/pytorch-lightning/pull/6416))
141141

142142

143+
- Fixed an exception in the layer summary when the model contains torch.jit scripted submodules ([#6511](https://github.com/PyTorchLightning/pytorch-lightning/pull/6511))
144+
145+
143146
## [1.2.3] - 2021-03-09
144147

145148
### Fixed

pytorch_lightning/core/memory.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import shutil
1717
import subprocess
1818
from collections import OrderedDict
19-
from typing import Any, Dict, List, Tuple, Union
19+
from typing import Any, Dict, List, Optional, Tuple, Union
2020

2121
import numpy as np
2222
import torch
@@ -71,14 +71,15 @@ def __init__(self, module: nn.Module):
7171
def __del__(self):
7272
self.detach_hook()
7373

74-
def _register_hook(self) -> RemovableHandle:
74+
def _register_hook(self) -> Optional[RemovableHandle]:
7575
"""
7676
Registers a hook on the module that computes the input- and output size(s) on the first forward pass.
7777
If the hook is called, it will remove itself from the from the module, meaning that
7878
recursive models will only record their input- and output shapes once.
79+
Registering hooks on :class:`~torch.jit.ScriptModule` is not supported.
7980
8081
Return:
81-
A handle for the installed hook.
82+
A handle for the installed hook, or ``None`` if registering the hook is not possible.
8283
"""
8384

8485
def hook(module, inp, out):
@@ -88,7 +89,10 @@ def hook(module, inp, out):
8889
self._out_size = parse_batch_shape(out)
8990
self._hook_handle.remove()
9091

91-
return self._module.register_forward_hook(hook)
92+
handle = None
93+
if not isinstance(self._module, torch.jit.ScriptModule):
94+
handle = self._module.register_forward_hook(hook)
95+
return handle
9296

9397
def detach_hook(self):
9498
"""

tests/core/test_memory.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,19 @@ def forward(self, x):
8888
return self.reduce(self.embed(x))
8989

9090

91+
class PartialScriptModel(LightningModule):
92+
""" A model which contains scripted layers. """
93+
94+
def __init__(self):
95+
super().__init__()
96+
self.layer1 = torch.jit.script(nn.Linear(5, 3))
97+
self.layer2 = nn.Linear(3, 2)
98+
self.example_input_array = torch.rand(2, 5)
99+
100+
def forward(self, x):
101+
return self.layer2(self.layer1(x))
102+
103+
91104
def test_invalid_weights_summmary():
92105
""" Test that invalid value for weights_summary raises an error. """
93106
with pytest.raises(MisconfigurationException, match='`mode` can be None, .* got temp'):
@@ -214,6 +227,15 @@ def test_summary_layer_types(mode):
214227
]
215228

216229

230+
@pytest.mark.parametrize('mode', [ModelSummary.MODE_FULL, ModelSummary.MODE_TOP])
231+
def test_summary_with_scripted_modules(mode):
232+
model = PartialScriptModel()
233+
summary = model.summarize(mode=mode)
234+
assert summary.layer_types == ["RecursiveScriptModule", "Linear"]
235+
assert summary.in_sizes == [UNKNOWN_SIZE, [2, 3]]
236+
assert summary.out_sizes == [UNKNOWN_SIZE, [2, 2]]
237+
238+
217239
@pytest.mark.parametrize('mode', [ModelSummary.MODE_FULL, ModelSummary.MODE_TOP])
218240
@pytest.mark.parametrize(['example_input', 'expected_size'], [
219241
pytest.param([], UNKNOWN_SIZE),
@@ -265,7 +287,7 @@ def test_empty_model_size(mode):
265287

266288

267289
@RunIf(min_gpus=1, amp_native=True)
268-
def test_model_size_precision(monkeypatch, tmpdir):
290+
def test_model_size_precision(tmpdir):
269291
""" Test model size for half and full precision. """
270292
model = PreCalculatedModel()
271293

0 commit comments

Comments
 (0)