Skip to content

Commit b229330

Browse files
tritsystemclaudeericspod
authored
fix(losses): BarlowTwinsLoss preserves float16/bfloat16 input dtype (#9103)
Fixes # . ### Description `BarlowTwinsLoss` silently upcasts `float16`/`bfloat16` inputs to `float32`. ```python import torch from monai.losses import BarlowTwinsLoss loss_fn = BarlowTwinsLoss() for dt in (torch.float64, torch.float32, torch.bfloat16, torch.float16): x = torch.randn(8, 16, dtype=dt) y = torch.randn(8, 16, dtype=dt) print(dt, "->", loss_fn(x, y).dtype) # float64 -> float64, float32 -> float32 # bfloat16 -> float32, float16 -> float32 <-- dtype lost ``` The cross-correlation matrix `c` correctly follows the input dtype (no explicit dtype anywhere in its construction), but: ```python c_diff = (c - torch.eye(c.size(0), device=c.device)).pow_(2) # FxF ``` `torch.eye(...)` is given `device=` but no `dtype=`, so it defaults to the global default dtype (`float32`). Subtracting it from a lower-precision `c` promotes the whole expression — and therefore the returned loss value — to `float32`. `float32`/`float64` inputs are unaffected since promotion only goes up, which is why this was never caught by the existing `float32`-only test cases. The second `torch.eye(...)` call on the next line (used only via `.bool()` to build a boolean mask) is unaffected by this — a `torch.eye` matrix's 0/1 values produce the identical boolean mask regardless of its dtype — so it's left as-is. ### Fix Add `dtype=c.dtype` to the first `torch.eye()` call. ### Verified - `float16`/`bfloat16`/`float32`/`float64` inputs all now return a loss at their own dtype. - All 5 existing `TEST_CASES` (byte-identical `float32` values), `test_ill_shape`, `test_ill_batch_size`, `test_with_cuda` pass unchanged. - Added `test_preserves_input_dtype`, parametrized over all four dtypes. Confirmed it fails on unpatched code (`float16`/`bfloat16` return `float32`) and passes with the fix. ### 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/losses/test_barlow_twins_loss.py` — 12 passed). - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. ### AI-assistance disclosure Found via a metamorphic dtype-preservation sweep (an automated check that a loss/op's output dtype should follow its input dtype), which flagged this exact function. Claude (Anthropic) was used to trace the root cause, write the fix and the test, and verify fail-on-unpatched / pass-with-fix directly by running the code, not assumed. 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 522697c commit b229330

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

‎monai/losses/barlow_twins.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
7878
c = torch.mm(input_norm.t(), target_norm) / batch_size # input_norm.t() is FxB, target_norm is BxF so c is FxF
7979

8080
# loss
81-
c_diff = (c - torch.eye(c.size(0), device=c.device)).pow_(2) # FxF
81+
c_diff = (c - torch.eye(c.size(0), dtype=c.dtype, device=c.device)).pow_(2) # FxF
8282
c_diff[~torch.eye(c.size(0), device=c.device).bool()] *= lambd_tensor
8383

8484
return c_diff.sum()

‎tests/losses/test_barlow_twins_loss.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,22 @@ def check_warning_raised(self):
104104
with self.assertWarns(Warning):
105105
BarlowTwinsLoss(lambd=5e-3, batch_size=1)
106106

107+
@parameterized.expand([(torch.float64,), (torch.float32,), (torch.bfloat16,), (torch.float16,)])
108+
def test_preserves_input_dtype(self, dtype):
109+
"""Check that the loss keeps the dtype of its inputs.
110+
111+
The cross-correlation matrix `c` follows the input dtype, but `c - torch.eye(...)` used to silently upcast
112+
to float32 whenever the dtype was below float32, because `torch.eye()` was never given an explicit dtype.
113+
114+
Args:
115+
dtype: floating-point dtype of the two input tensors, which the returned loss must also have.
116+
"""
117+
loss = BarlowTwinsLoss(lambd=5e-3)
118+
i = torch.randn(4, 8, dtype=dtype)
119+
j = torch.randn(4, 8, dtype=dtype)
120+
output = loss(i, j)
121+
self.assertEqual(output.dtype, dtype)
122+
107123

108124
if __name__ == "__main__":
109125
unittest.main()

0 commit comments

Comments
 (0)