π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: move loss and color constructor tensors with modules (#5664)
AhmetHakanBezirc6a639b6ad29
diff --git a/changelog.d/5664.fixed.md b/changelog.d/5664.fixed.mdnew file mode 100644index 000000000..5d9341ba4--- /dev/null+++ b/changelog.d/5664.fixed.md@@ -0,0 +1 @@+Move constructor tensor weights and coefficients with `.to()` in DiceLoss, FocalLoss, BinaryFocalLossWithLogits, LovaszSoftmaxLoss, RgbToRgba, BgrToRgba and AddWeighted, preserving explicit Parameters and checkpoint keys.diff --git a/kornia/color/rgb.py b/kornia/color/rgb.pyindex 7a91bf208..c163cfe4b 100644--- a/kornia/color/rgb.py+++ b/kornia/color/rgb.py@@ -508,7 +508,10 @@ class RgbToRgba(nn.Module):def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:super().__init__()- self.alpha_val = alpha_val+ if isinstance(alpha_val, torch.Tensor) and not isinstance(alpha_val, nn.Parameter):+ self.register_buffer("alpha_val", alpha_val, persistent=False)+ else:+ self.alpha_val = alpha_valdef forward(self, image: torch.Tensor) -> torch.Tensor:"""Convert an RGB tensor to RGBA.@@ -556,7 +559,10 @@ class BgrToRgba(nn.Module):def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:super().__init__()- self.alpha_val = alpha_val+ if isinstance(alpha_val, torch.Tensor) and not isinstance(alpha_val, nn.Parameter):+ self.register_buffer("alpha_val", alpha_val, persistent=False)+ else:+ self.alpha_val = alpha_valdef forward(self, image: torch.Tensor) -> torch.Tensor:"""Append this module's alpha channel to the input tensor.diff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 9847f422e..726dbfb92 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -117,9 +117,18 @@ class AddWeighted(nn.Module):self, alpha: Union[float, torch.Tensor], beta: Union[float, torch.Tensor], gamma: Union[float, torch.Tensor]) -> None:super().__init__()- self.alpha = alpha- self.beta = beta- self.gamma = gamma+ if isinstance(alpha, torch.Tensor) and not isinstance(alpha, nn.Parameter):+ self.register_buffer("alpha", alpha, persistent=False)+ else:+ self.alpha = alpha+ if isinstance(beta, torch.Tensor) and not isinstance(beta, nn.Parameter):+ self.register_buffer("beta", beta, persistent=False)+ else:+ self.beta = beta+ if isinstance(gamma, torch.Tensor) and not isinstance(gamma, nn.Parameter):+ self.register_buffer("gamma", gamma, persistent=False)+ else:+ self.gamma = gammadef forward(self, src1: torch.Tensor, src2: torch.Tensor) -> torch.Tensor:"""Compute a weighted sum of two tensors with a scalar bias term.diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex 9c4ec8d3c..65d0a94ce 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -234,7 +234,10 @@ class DiceLoss(nn.Module):super().__init__()self.average = averageself.eps = eps- self.weight = weight+ if isinstance(weight, nn.Parameter):+ self.weight = weight+ else:+ self.register_buffer("weight", weight, persistent=False)self.ignore_index = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 495f227c9..7c1d5a31a 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -225,7 +225,10 @@ class FocalLoss(nn.Module):self.alpha: Optional[float] = alphaself.gamma: float = gammaself.reduction: str = reduction- self.weight: Optional[torch.Tensor] = weight+ if isinstance(weight, nn.Parameter):+ self.weight = weight+ else:+ self.register_buffer("weight", weight, persistent=False)self.ignore_index: Optional[int] = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:@@ -435,8 +438,14 @@ class BinaryFocalLossWithLogits(nn.Module):self.alpha: Optional[float] = alphaself.gamma: float = gammaself.reduction: str = reduction- self.pos_weight: Optional[torch.Tensor] = pos_weight- self.weight: Optional[torch.Tensor] = weight+ if isinstance(pos_weight, nn.Parameter):+ self.pos_weight = pos_weight+ else:+ self.register_buffer("pos_weight", pos_weight, persistent=False)+ if isinstance(weight, nn.Parameter):+ self.weight = weight+ else:+ self.register_buffer("weight", weight, persistent=False)self.ignore_index: Optional[int] = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pyindex 656db9c6b..acb1b9f62 100644--- a/kornia/losses/lovasz_softmax.py+++ b/kornia/losses/lovasz_softmax.py@@ -205,7 +205,10 @@ class LovaszSoftmaxLoss(nn.Module):def __init__(self, weight: Optional[Tensor] = None) -> None:super().__init__()- self.weight = weight+ if isinstance(weight, nn.Parameter):+ self.weight = weight+ else:+ self.register_buffer("weight", weight, persistent=False)def forward(self, pred: Tensor, target: Tensor) -> Tensor:"""Compute multi-class Lovasz-Softmax loss.diff --git a/tests/test_module_constructor_tensors.py b/tests/test_module_constructor_tensors.pynew file mode 100644index 000000000..c698b6d42--- /dev/null+++ b/tests/test_module_constructor_tensors.py@@ -0,0 +1,106 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++import kornia+++def _module(case, value):+ constructors = {+ "dice": lambda: kornia.losses.DiceLoss(weight=value),+ "focal": lambda: kornia.losses.FocalLoss(alpha=0.25, weight=value),+ "binary_weight": lambda: kornia.losses.BinaryFocalLossWithLogits(alpha=0.25, weight=value),+ "binary_pos_weight": lambda: kornia.losses.BinaryFocalLossWithLogits(alpha=0.25, pos_weight=value),+ "lovasz": lambda: kornia.losses.LovaszSoftmaxLoss(weight=value),+ "rgb": lambda: kornia.color.RgbToRgba(value),+ "bgr": lambda: kornia.color.BgrToRgba(value),+ "alpha": lambda: kornia.enhance.AddWeighted(value, 0.5, 0.1),+ "beta": lambda: kornia.enhance.AddWeighted(0.5, value, 0.1),+ "gamma": lambda: kornia.enhance.AddWeighted(0.5, 0.5, value),+ }+ name = "pos_weight" if case == "binary_pos_weight" else "weight"+ if case in ("rgb", "bgr"):+ name = "alpha_val"+ elif case in ("alpha", "beta", "gamma"):+ name = case+ return constructors[case](), name+++CASES = ["dice", "focal", "binary_weight", "binary_pos_weight", "lovasz", "rgb", "bgr", "alpha", "beta", "gamma"]+++def _value(case):+ return torch.full((1, 1, 2, 2) if case in ("rgb", "bgr", "alpha", "beta", "gamma") else (3,), 0.7)+++def _forward(module, case, device, dtype):+ pred = torch.linspace(-0.7, 0.8, 12, device=device, dtype=dtype).reshape(1, 3, 2, 2)+ if case in ("rgb", "bgr"):+ return module(pred)+ if case in ("alpha", "beta", "gamma"):+ return module(pred, pred * 0.3)+ if case.startswith("binary"):+ return module(pred, torch.ones_like(pred))+ target = torch.tensor([[[0, 1], [2, 1]]], device=device)+ return module(pred, target)++[email protected]("case", CASES)+def test_constructor_tensor_follows_conversion(case, device, dtype):+ original = _value(case).requires_grad_()+ module, name = _module(case, original)+ module.to(device=device, dtype=dtype)+ converted = getattr(module, name)+ assert converted.device == torch.device(device)+ assert converted.dtype == dtype+ assert name in dict(module.named_buffers())+ assert dict(module.named_parameters()) == {}+ assert dict(module.state_dict()) == {}+ expected, _ = _module(case, original.to(device=device, dtype=dtype))+ actual = _forward(module, case, device, dtype)+ torch.testing.assert_close(actual, _forward(expected, case, device, dtype))+ actual.sum().backward()+ assert original.grad is not None+ assert torch.isfinite(original.grad).all()++[email protected]("case", CASES)+def test_explicit_parameter_remains_trainable(case, device, dtype):+ parameter = torch.nn.Parameter(_value(case))+ module, name = _module(case, parameter)+ assert dict(module.named_parameters())[name] is parameter+ module.to(device=device, dtype=dtype)+ stored = getattr(module, name)+ assert isinstance(stored, torch.nn.Parameter)+ assert stored.device == torch.device(device)+ assert stored.dtype == dtype+ assert dict(module.named_parameters())[name] is stored+ assert name in module.state_dict()+ _forward(module, case, device, dtype).sum().backward()+ assert stored.grad is not None+ assert torch.isfinite(stored.grad).all()++[email protected]("case", CASES)+def test_constructor_tensor_moves_to_meta(case):+ module, name = _module(case, _value(case))+ module.to(device="meta")+ assert getattr(module, name).device == torch.device("meta")+ if case in ("rgb", "bgr", "alpha", "beta", "gamma"):+ assert _forward(module, case, "meta", torch.float32).device == torch.device("meta")