Skip to content

Commit cb35d45

Browse files
tritsystemclaudeericspod
authored
fix(networks): AffineHead follows the module's dtype, not just device (#9104)
Fixes # . ### Description `GlobalNet`/`LocalNet` (both build on `AffineHead`) crash immediately on the first half-precision forward call: ```python import torch from monai.networks.nets import GlobalNet net = GlobalNet(image_size=[16,16], spatial_dims=2, in_channels=1, num_channel_initial=4, depth=2).half() net(torch.randn(1, 1, 16, 16, dtype=torch.float16)) # RuntimeError: expected scalar type Half but found Float ``` `AffineHead.grid` is a plain attribute (`torch.stack(...).to(dtype=torch.float)` in `get_reference_grid`, never `register_buffer`'d), so `.half()` on the containing module never touches it. `forward()` re-derives only its *device* every call: ```python self.grid = self.grid.to(device=f.device) ``` never its dtype. So after `.half()`, `theta` (from `self.fc`, whose weights *do* move) becomes `float16`, but `self.grid` stays `float32`, and `affine_transform`'s `torch.einsum(..., grid_padded, theta...)` raises immediately since it requires matching dtypes. ### Fix Re-derive dtype alongside device every forward call: ```python self.grid = self.grid.to(device=f.device, dtype=f.dtype) ``` `f`'s dtype is a safe reference point here: `self.fc(f.reshape(...))` (the very next line) already requires `f`'s dtype to match `self.fc`'s weights for that call to succeed, so by the time `affine_transform(theta) - self.grid` runs, `f.dtype` is guaranteed consistent with `theta`'s dtype. ### Verified - Half-precision forward no longer crashes, on `AffineHead` directly and through the full `GlobalNet` network; output is `float16` at the correct shape. - `float32` path is unaffected (`f.dtype` was already `torch.float` in that case, so this is a no-op there). - Added `test_half_precision_forward` to `test_globalnet.py` (parametrized over the existing `TEST_CASES_GLOBAL_NET`). Confirmed it fails with the exact `RuntimeError` above on unpatched code, passes with the fix. - Full existing `test_globalnet.py` and `test_regunet.py` suites pass unchanged (8/8 and 4/4 real tests respectively). ### Types of changes - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [x] Quick tests passed locally (`pytest tests/networks/nets/test_globalnet.py tests/networks/nets/regunet/test_regunet.py`). - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. ### AI-assistance disclosure Found via the same metamorphic dtype-preservation sweep that flagged #9103 (checking whether a module's registered state actually follows `.to()`/`.half()`). Claude (Anthropic) was used to trace the root cause, write the fix and the test, and verify fail-on-unpatched / pass-with-fix by actually running the code. I reviewed the root cause, the fix, and the test before opening this PR. --------- Signed-off-by: tritsystem <gbranaa4@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent e74ef7d commit cb35d45

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

‎monai/networks/nets/regunet.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,19 @@ def affine_transform(self, theta: torch.Tensor):
294294
return grid_warped
295295

296296
def forward(self, x: list[torch.Tensor], image_size: list[int]) -> torch.Tensor:
297+
"""
298+
Predict an affine transform from the first feature map and return it as a displacement field.
299+
300+
Args:
301+
x: feature maps from the network; only the first, ``x[0]``, is used. The reference grid is moved to its
302+
device and dtype, so a network cast to half precision stays in half precision.
303+
image_size: spatial size of the input image; not used by this head.
304+
305+
Returns:
306+
The displacement field, the warped reference grid minus the reference grid.
307+
"""
297308
f = x[0]
298-
self.grid = self.grid.to(device=f.device)
309+
self.grid = self.grid.to(device=f.device, dtype=f.dtype)
299310
theta = self.fc(f.reshape(f.shape[0], -1))
300311
if self.save_theta:
301312
self.theta = theta.detach()

‎tests/networks/nets/test_globalnet.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,26 @@ def test_script(self, input_param, input_shape, _):
9898
test_data = torch.randn(input_shape)
9999
test_script_save(net, test_data)
100100

101+
@parameterized.expand(TEST_CASES_GLOBAL_NET)
102+
def test_half_precision_forward(self, input_param, input_shape, expected_shape):
103+
"""Check that a GlobalNet cast to half precision can run a forward pass and returns float16.
104+
105+
`AffineHead.grid` used to be moved by device only, so casting the network left it at float32 while theta
106+
became float16, and the einsum in `affine_transform` raised `RuntimeError: expected scalar type Half but
107+
found Float` on the first half-precision forward call.
108+
109+
Args:
110+
input_param: keyword arguments used to build the GlobalNet.
111+
input_shape: shape of the random float16 input.
112+
expected_shape: shape the returned displacement field must have.
113+
"""
114+
net = GlobalNet(**input_param).half()
115+
with eval_mode(net):
116+
img = torch.randn(input_shape, dtype=torch.float16)
117+
result = net(img)
118+
self.assertEqual(result.dtype, torch.float16)
119+
self.assertEqual(result.shape, expected_shape)
120+
101121

102122
if __name__ == "__main__":
103123
unittest.main()

0 commit comments

Comments
 (0)