Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor focal loss and add gpu test

edgarriba9600409847f3
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 361b29132..dc7a713b0 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -10,6 +10,60 @@ from kornia.utils import one_hot
# based on:
# https://github.com/zhezh/focalloss/blob/master/focalloss.py
+def focal_loss(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ alpha: float,
+ gamma: float = 2.0,
+ reduction: str = 'none',
+ eps: float = 1e-8) -> torch.Tensor:
+ r"""Function that computes Focal loss.
+
+ See :class:`~kornia.losses.FocalLoss` for details.
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}"
+ .format(input.shape))
+
+ if not input.shape[-2:] == target.shape[-2:]:
+ raise ValueError("input and target shapes must be the same. Got: {}"
+ .format(input.shape, input.shape))
+
+ if not input.device == target.device:
+ raise ValueError(
+ "input and target must be in the same device. Got: {}" .format(
+ input.device, target.device))
+
+ # compute softmax over the classes axis
+ input_soft: torch.Tensor = F.softmax(input, dim=1) + eps
+
+ # create the labels one hot tensor
+ target_one_hot: torch.Tensor = one_hot(
+ target, num_classes=input.shape[1],
+ device=input.device, dtype=input.dtype)
+
+ # compute the actual focal loss
+ weight = torch.pow(1. - input_soft, gamma)
+
+ focal = -alpha * weight * torch.log(input_soft)
+ loss_tmp = torch.sum(target_one_hot * focal, dim=1)
+
+ if reduction == 'none':
+ loss = loss_tmp
+ elif reduction == 'mean':
+ loss = torch.mean(loss_tmp)
+ elif reduction == 'sum':
+ loss = torch.sum(loss_tmp)
+ else:
+ raise NotImplementedError("Invalid reduction mode: {}"
+ .format(reduction))
+ return loss
+
+
class FocalLoss(nn.Module):
r"""Criterion that computes Focal loss.
@@ -26,7 +80,7 @@ class FocalLoss(nn.Module):
Arguments:
alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.
gamma (float): Focusing parameter :math:`\gamma >= 0`.
- reduction (Optional[str]): Specifies the reduction to apply to the
+ reduction (str, optional): Specifies the reduction to apply to the
output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,
‘mean’: the sum of the output will be divided by the number of elements
in the output, ‘sum’: the output will be summed. Default: ‘none’.
@@ -49,69 +103,16 @@ class FocalLoss(nn.Module):
[1] https://arxiv.org/abs/1708.02002
"""
- def __init__(self, alpha: float, gamma: Optional[float] = 2.0,
- reduction: Optional[str] = 'none') -> None:
+ def __init__(self, alpha: float, gamma: float = 2.0,
+ reduction: str = 'none') -> None:
super(FocalLoss, self).__init__()
self.alpha: float = alpha
- self.gamma: torch.Tensor = torch.tensor(gamma)
- self.reduction: Optional[str] = reduction
+ self.gamma: float = gamma
+ self.reduction: str = reduction
self.eps: float = 1e-6
def forward( # type: ignore
self,
input: torch.Tensor,
target: torch.Tensor) -> torch.Tensor:
- if not torch.is_tensor(input):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
- if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}"
- .format(input.shape))
- if not input.shape[-2:] == target.shape[-2:]:
- raise ValueError("input and target shapes must be the same. Got: {}"
- .format(input.shape, input.shape))
- if not input.device == target.device:
- raise ValueError(
- "input and target must be in the same device. Got: {}" .format(
- input.device, target.device))
- # compute softmax over the classes axis
- input_soft = F.softmax(input, dim=1) + self.eps
-
- # create the labels one hot tensor
- target_one_hot = one_hot(target, num_classes=input.shape[1],
- device=input.device, dtype=input.dtype)
-
- # compute the actual focal loss
- weight = torch.pow(torch.tensor(1.) - input_soft,
- self.gamma.to(input.dtype))
- focal = -self.alpha * weight * torch.log(input_soft)
- loss_tmp = torch.sum(target_one_hot * focal, dim=1)
-
- if self.reduction == 'none':
- loss = loss_tmp
- elif self.reduction == 'mean':
- loss = torch.mean(loss_tmp)
- elif self.reduction == 'sum':
- loss = torch.sum(loss_tmp)
- else:
- raise NotImplementedError("Invalid reduction mode: {}"
- .format(self.reduction))
- return loss
-
-
-######################
-# functional interface
-######################
-
-
-def focal_loss(
- input: torch.Tensor,
- target: torch.Tensor,
- alpha: float,
- gamma: Optional[float] = 2.0,
- reduction: Optional[str] = 'none') -> torch.Tensor:
- r"""Function that computes Focal loss.
-
- See :class:`~kornia.losses.FocalLoss` for details.
- """
- return FocalLoss(alpha, gamma, reduction)(input, target)
+ return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.eps)
diff --git a/test/test_losses.py b/test/test_losses.py
index 1bfb7acb0..e0527a4d8 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -2,6 +2,7 @@ import pytest
import kornia
import kornia.testing as utils # test utils
+from test.common import device
import math
import torch
@@ -10,21 +11,21 @@ from torch.testing import assert_allclose
class TestFocalLoss:
- def _test_smoke_none(self):
+ def test_smoke_none(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
assert kornia.losses.focal_loss(
logits, labels, alpha=0.5, gamma=2.0, reduction="none"
).shape == (2, 3, 2)
- def _test_smoke_sum(self):
+ def test_smoke_sum(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
assert (
kornia.losses.focal_loss(
@@ -32,11 +33,11 @@ class TestFocalLoss:
).shape == ()
)
- def _test_smoke_mean(self):
+ def test_smoke_mean(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
assert (
kornia.losses.focal_loss(
@@ -45,15 +46,15 @@ class TestFocalLoss:
)
# TODO: implement me
- def _test_jit(self):
+ def test_jit(self, device):
pass
- def _test_gradcheck(self):
+ def test_gradcheck(self, device):
num_classes = 3
alpha, gamma = 0.5, 2.0 # for focal loss
- logits = torch.rand(2, num_classes, 3, 2)
+ logits = torch.rand(2, num_classes, 3, 2).to(device)
labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.long()
+ labels = labels.to(device).long()
logits = utils.tensor_to_gradcheck_var(logits) # to var
assert gradcheck(
@@ -62,15 +63,9 @@ class TestFocalLoss:
raise_exception=True,
)
- def test_run_all(self):
- self._test_smoke_none()
- self._test_smoke_sum()
- self._test_smoke_mean()
- self._test_gradcheck()
-
class TestTverskyLoss:
- def _test_smoke(self):
+ def test_smoke(self):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2)
labels = torch.rand(2, 3, 2) * num_classes
@@ -79,7 +74,7 @@ class TestTverskyLoss:
criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
loss = criterion(logits, labels)
- def _test_all_zeros(self):
+ def test_all_zeros(self):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2)
logits[:, 0] = 10.0
@@ -92,10 +87,10 @@ class TestTverskyLoss:
assert pytest.approx(loss.item(), 0.0)
# TODO: implement me
- def _test_jit(self):
+ def test_jit(self):
pass
- def _test_gradcheck(self):
+ def test_gradcheck(self):
num_classes = 3
alpha, beta = 0.5, 0.5 # for tversky loss
logits = torch.rand(2, num_classes, 3, 2)
@@ -109,14 +104,9 @@ class TestTverskyLoss:
raise_exception=True,
)
- def test_run_all(self):
- self._test_smoke()
- self._test_all_zeros()
- self._test_gradcheck()
-
class TestDiceLoss:
- def _test_smoke(self):
+ def test_smoke(self):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2)
labels = torch.rand(2, 3, 2) * num_classes
@@ -125,7 +115,7 @@ class TestDiceLoss:
criterion = kornia.losses.DiceLoss()
loss = criterion(logits, labels)
- def _test_all_zeros(self):
+ def test_all_zeros(self):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2)
logits[:, 0] = 10.0
@@ -138,10 +128,10 @@ class TestDiceLoss:
assert pytest.approx(loss.item(), 0.0)
# TODO: implement me
- def _test_jit(self):
+ def test_jit(self):
pass
- def _test_gradcheck(self):
+ def test_gradcheck(self):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2)
labels = torch.rand(2, 3, 2) * num_classes
@@ -152,11 +142,6 @@ class TestDiceLoss:
kornia.losses.dice_loss, (logits, labels), raise_exception=True
)
- def test_run_all(self):
- self._test_smoke()
- self._test_all_zeros()
- self._test_gradcheck()
-
class TestDepthSmoothnessLoss:
def _test_smoke(self):