🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Add tpu support for the losses module (#834)
Edgar Riba0388a3b7a0cb
diff --git a/docker/tpu-tests/tpu_test_cases.jsonnet b/docker/tpu-tests/tpu_test_cases.jsonnetindex 5d17cd817..b7bd817e3 100644--- a/docker/tpu-tests/tpu_test_cases.jsonnet+++ b/docker/tpu-tests/tpu_test_cases.jsonnet@@ -23,7 +23,7 @@ local tputests = base.BaseTest {python -c "import torch; print(torch.__version__)"python -c "import torch_xla; print(torch_xla.__version__)"python -c "import kornia; print(kornia.__version__)"- pytest -v kornia/test/color kornia/test/enhance kornia/test/filters --device tpu --dtype float32 -k "not grad"+ pytest -v kornia/test/color kornia/test/enhance kornia/test/filters kornia/test/test_losses.py --device tpu --dtype float32 -k "not grad"test_exit_code=$?echo "\nFinished running commands.\n"test $test_exit_code -eq 0diff --git a/docs/source/references.bib b/docs/source/references.bibindex 9993eaf74..1ea090974 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -33,3 +33,21 @@booktitle = {International Conference on Computer Vision (ICCV)},year={2019},}++@misc{lin2018focal,+ title={Focal Loss for Dense Object Detection},+ author={Tsung-Yi Lin and Priya Goyal and Ross Girshick and Kaiming He and Piotr Dollár},+ year={2018},+ eprint={1708.02002},+ archivePrefix={arXiv},+ primaryClass={cs.CV}+}++@misc{salehi2017tversky,+ title={Tversky loss function for image segmentation using 3D fully convolutional deep networks},+ author={Seyed Sadegh Mohseni Salehi and Deniz Erdogmus and Ali Gholipour},+ year={2017},+ eprint={1706.05721},+ archivePrefix={arXiv},+ primaryClass={cs.CV}+}diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex a6d428e5a..5fd993252 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -19,15 +19,31 @@ def _gradient_y(img: torch.Tensor) -> torch.Tensor:def inverse_depth_smoothness_loss(idepth: torch.Tensor,image: torch.Tensor) -> torch.Tensor:- r"""Computes image-aware inverse depth smoothness loss.+ r"""Criterion that computes image-aware inverse depth smoothness loss.++ .. math::++ \text{loss} = \left | \partial_x d_{ij} \right | e^{-\left \|+ \partial_x I_{ij} \right \|} + \left |+ \partial_y d_{ij} \right | e^{-\left \| \partial_y I_{ij} \right \|}- See :class:`~kornia.losses.InverseDepthSmoothnessLoss` for details.+ Args:+ idepth (torch.Tensor): tensor with the inverse depth with shape :math:`(N, 1, H, W)`.+ image (torch.Tensor): tensor with the input image with shape :math:`(N, 3, H, W)`.++ Return:+ torch.Tensor: a scalar with the computed loss.++ Examples:+ >>> idepth = torch.rand(1, 1, 4, 5)+ >>> image = torch.rand(1, 3, 4, 5)+ >>> loss = inverse_depth_smoothness_loss(idepth, image)"""- if not torch.is_tensor(idepth):+ if not isinstance(idepth, torch.Tensor):raise TypeError("Input idepth type is not a torch.Tensor. Got {}".format(type(idepth)))- if not torch.is_tensor(image):+ if not isinstance(image, torch.Tensor):raise TypeError("Input image type is not a torch.Tensor. Got {}".format(type(image)))@@ -68,6 +84,7 @@ def inverse_depth_smoothness_loss(# apply image weights to depthsmoothness_x: torch.Tensor = torch.abs(idepth_dx * weights_x)smoothness_y: torch.Tensor = torch.abs(idepth_dy * weights_y)+return torch.mean(smoothness_x) + torch.mean(smoothness_y)@@ -80,14 +97,12 @@ class InverseDepthSmoothnessLoss(nn.Module):\partial_x I_{ij} \right \|} + \left |\partial_y d_{ij} \right | e^{-\left \| \partial_y I_{ij} \right \|}-Shape:- Inverse Depth: :math:`(N, 1, H, W)`- Image: :math:`(N, 3, H, W)`- Output: scalar- Examples::-+ Examples:>>> idepth = torch.rand(1, 1, 4, 5)>>> image = torch.rand(1, 3, 4, 5)>>> smooth = InverseDepthSmoothnessLoss()@@ -97,5 +112,5 @@ class InverseDepthSmoothnessLoss(nn.Module):def __init__(self) -> None:super(InverseDepthSmoothnessLoss, self).__init__()- def forward(self, idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor: # type:ignore+ def forward(self, idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor:return inverse_depth_smoothness_loss(idepth, image)diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex 07fc22c7f..2f6ab68c5 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -11,11 +11,44 @@ from kornia.utils.one_hot import one_hot# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.pydef dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:- r"""Function that computes Sørensen-Dice Coefficient loss.+ r"""Criterion that computes Sørensen-Dice Coefficient loss.++ According to [1], we compute the Sørensen-Dice Coefficient as follows:++ .. math::++ \text{Dice}(x, class) = \frac{2 |X| \cap |Y|}{|X| + |Y|}- See :class:`~kornia.losses.DiceLoss` for details.+ Where:+ - :math:`X` expects to be the scores of each class.+ - :math:`Y` expects to be the one-hot tensor with the class labels.++ the loss, is finally computed as:++ .. math::++ \text{loss}(x, class) = 1 - \text{Dice}(x, class)++ Reference:+ [1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient++ Args:+ input (torch.Tensor): logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.+ labels (torch.Tensor): labels tensor with shape :math:`(N, H, W)` where each value+ is :math:`0 ≤ targets[i] ≤ C−1`.+ eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.++ Return:+ torch.Tensor: the computed loss.++ Example:+ >>> N = 5 # num_classes+ >>> input = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = dice_loss(input, target)+ >>> output.backward()"""- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))@@ -46,6 +79,7 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> tcardinality = torch.sum(input_soft + target_one_hot, dims)dice_score = 2. * intersection / (cardinality + eps)+return torch.mean(-dice_score + 1.)@@ -58,7 +92,7 @@ class DiceLoss(nn.Module):\text{Dice}(x, class) = \frac{2 |X| \cap |Y|}{|X| + |Y|}- where:+ Where:- :math:`X` expects to be the scores of each class.- :math:`Y` expects to be the one-hot tensor with the class labels.@@ -68,28 +102,29 @@ class DiceLoss(nn.Module):\text{loss}(x, class) = 1 - \text{Dice}(x, class)- [1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient+ Reference:+ [1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient++ Args:+ eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.- Target: :math:`(N, H, W)` where each value is:math:`0 ≤ targets[i] ≤ C−1`.- Examples:+ Example:>>> N = 5 # num_classes- >>> loss = DiceLoss()+ >>> criterion = DiceLoss()>>> input = torch.randn(1, N, 3, 5, requires_grad=True)>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)- >>> output = loss(input, target)+ >>> output = criterion(input, target)>>> output.backward()"""- def __init__(self) -> None:+ def __init__(self, eps: float = 1e-8) -> None:super(DiceLoss, self).__init__()- self.eps: float = 1e-6+ self.eps: float = eps- def forward( # type: ignore- self,- input: torch.Tensor,- target: torch.Tensor) -> torch.Tensor:+ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:return dice_loss(input, target, self.eps)diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.pyindex 6bb4decfa..483c31033 100644--- a/kornia/losses/divergence.py+++ b/kornia/losses/divergence.py@@ -5,7 +5,7 @@ import torchimport torch.nn.functional as F-def _kl_div_2d(p, q):+def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:# D_KL(P || Q)batch, chans, height, width = p.shapeunsummed_kl = F.kl_div(@@ -17,7 +17,7 @@ def _kl_div_2d(p, q):return kl_values-def _js_div_2d(p, q):+def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:# JSD(P || Q)m = 0.5 * (p + q)return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)@@ -25,11 +25,10 @@ def _js_div_2d(p, q):# TODO: add this to the main module-def _reduce_loss(losses, reduction):+def _reduce_loss(losses: torch.Tensor, reduction: str) -> torch.Tensor:if reduction == 'none':return losses- else:- return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)+ return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)def js_div_loss_2d(diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 889572e6d..01835e732 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -17,11 +17,39 @@ def focal_loss(gamma: float = 2.0,reduction: str = 'none',eps: float = 1e-8) -> torch.Tensor:- r"""Function that computes Focal loss.+ r"""Criterion that computes Focal loss.++ According to :cite:`lin2018focal`, the Focal loss is computed as follows:++ .. math::++ \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)++ Where:+ - :math:`p_t` is the model's estimated probability for each class.++ Args:+ input (torch.Tensor): logits tensor with shape :math:`(N, C, *)` where C = number of classes.+ target (torch.Tensor): labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C−1`.+ alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.+ gamma (float, optional): Focusing parameter :math:`\gamma >= 0`. Default 2.+ 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’.+ eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.++ Return:+ torch.Tensor: the computed loss.- See :class:`~kornia.losses.FocalLoss` for details.+ Example:+ >>> N = 5 # num_classes+ >>> input = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = focal_loss(input, target, alpha=0.5, gamma=2.0, reduction='mean')+ >>> output.backward()"""- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))@@ -73,54 +101,48 @@ def focal_loss(class FocalLoss(nn.Module):r"""Criterion that computes Focal loss.- According to [1], the Focal loss is computed as follows:+ According to :cite:`lin2018focal`, the Focal loss is computed as follows:.. math::\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)- where:+ Where:- :math:`p_t` is the model's estimated probability for each class.-- Arguments:+ Args:alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.- gamma (float): Focusing parameter :math:`\gamma >= 0`.+ gamma (float, optional): Focusing parameter :math:`\gamma >= 0`. Default 2.reduction (str, optional): Specifies the reduction to apply to theoutput: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,‘mean’: the sum of the output will be divided by the number of elementsin the output, ‘sum’: the output will be summed. Default: ‘none’.+ eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.Shape:- Input: :math:`(N, C, *)` where C = number of classes.- Target: :math:`(N, *)` where each value is:math:`0 ≤ targets[i] ≤ C−1`.- Examples:+ Example:>>> N = 5 # num_classes>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}- >>> loss = FocalLoss(**kwargs)+ >>> criterion = FocalLoss(**kwargs)>>> input = torch.randn(1, N, 3, 5, requires_grad=True)>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)- >>> output = loss(input, target)+ >>> output = criterion(input, target)>>> output.backward()-- References:- [1] https://arxiv.org/abs/1708.02002"""def __init__(self, alpha: float, gamma: float = 2.0,- reduction: str = 'none') -> None:+ reduction: str = 'none', eps: float = 1e-8) -> None:super(FocalLoss, self).__init__()self.alpha: float = alphaself.gamma: float = gammaself.reduction: str = reduction- self.eps: float = 1e-6+ self.eps: float = eps- def forward( # type: ignore- self,- input: torch.Tensor,- target: torch.Tensor) -> torch.Tensor:+ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.eps)diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.pyindex 6167b3681..dd0dc99cd 100644--- a/kornia/losses/tversky.py+++ b/kornia/losses/tversky.py@@ -10,13 +10,49 @@ from kornia.utils.one_hot import one_hot# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py-def tversky_loss(input: torch.Tensor, target: torch.Tensor,- alpha: float, beta: float, eps: float = 1e-8) -> torch.Tensor:- r"""Function that computes Tversky loss.+def tversky_loss(input: torch.Tensor,+ target: torch.Tensor,+ alpha: float, beta: float,+ eps: float = 1e-8) -> torch.Tensor:+ r"""Criterion that computes Tversky Coefficient loss.++ According to :cite:`salehi2017tversky`, we compute the Tversky Coefficient as follows:++ .. math::++ \text{S}(P, G, \alpha; \beta) =+ \frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}- See :class:`~kornia.losses.TverskyLoss` for details.+ Where:+ - :math:`P` and :math:`G` are the predicted and ground truth binary+ labels.+ - :math:`\alpha` and :math:`\beta` control the magnitude of the+ penalties for FPs and FNs, respectively.++ Note:+ - :math:`\alpha = \beta = 0.5` => dice coeff+ - :math:`\alpha = \beta = 1` => tanimoto coeff+ - :math:`\alpha + \beta = 1` => F beta coeff++ Args:+ input (torch.Tensor): logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.+ target (torch.Tensor): labels tensor with shape :math:`(N, H, W)` where each value+ is :math:`0 ≤ targets[i] ≤ C−1`.+ alpha (float): the first coefficient in the denominator.+ beta (float): the second coefficient in the denominator.+ eps (float, optional): scalar for numerical stability. Default: 1e-8.++ Return:+ torch.Tensor: the computed loss.++ Example:+ >>> N = 5 # num_classes+ >>> input = torch.randn(1, N, 3, 5, requires_grad=True)+ >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)+ >>> output = tversky_loss(input, target, alpha=0.5, beta=0.5)+ >>> output.backward()"""- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))@@ -50,30 +86,36 @@ def tversky_loss(input: torch.Tensor, target: torch.Tensor,numerator = intersectiondenominator = intersection + alpha * fps + beta * fnstversky_loss = numerator / (denominator + eps)+return torch.mean(-tversky_loss + 1.)class TverskyLoss(nn.Module):r"""Criterion that computes Tversky Coefficient loss.- According to [1], we compute the Tversky Coefficient as follows:+ According to :cite:`salehi2017tversky`, we compute the Tversky Coefficient as follows:.. math::\text{S}(P, G, \alpha; \beta) =\frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}- where:+ Where:- :math:`P` and :math:`G` are the predicted and ground truth binarylabels.- :math:`\alpha` and :math:`\beta` control the magnitude of thepenalties for FPs and FNs, respectively.- Notes:+ Note:- :math:`\alpha = \beta = 0.5` => dice coeff- :math:`\alpha = \beta = 1` => tanimoto coeff- :math:`\alpha + \beta = 1` => F beta coeff+ Args:+ alpha (float): the first coefficient in the denominator.+ beta (float): the second coefficient in the denominator.+ eps (float, optional): scalar for numerical stability. Default: 1e-8.+Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.- Target: :math:`(N, H, W)` where each value is@@ -81,14 +123,11 @@ class TverskyLoss(nn.Module):Examples:>>> N = 5 # num_classes- >>> loss = TverskyLoss(alpha=0.5, beta=0.5)+ >>> criterion = TverskyLoss(alpha=0.5, beta=0.5)>>> input = torch.randn(1, N, 3, 5, requires_grad=True)>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)- >>> output = loss(input, target)+ >>> output = criterion(input, target)>>> output.backward()-- References:- [1]: https://arxiv.org/abs/1706.05721"""def __init__(self, alpha: float, beta: float, eps: float = 1e-8) -> None:@@ -97,8 +136,5 @@ class TverskyLoss(nn.Module):self.beta: float = betaself.eps: float = eps- def forward( # type: ignore- self,- input: torch.Tensor,- target: torch.Tensor) -> torch.Tensor:+ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:return tversky_loss(input, target, self.alpha, self.beta, self.eps)diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.pyindex 958e935b4..3c1f41ee8 100644--- a/kornia/utils/one_hot.py+++ b/kornia/utils/one_hot.py@@ -7,7 +7,7 @@ def one_hot(labels: torch.Tensor,num_classes: int,device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,- eps: Optional[float] = 1e-6) -> torch.Tensor:+ eps: float = 1e-6) -> torch.Tensor:r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor.Args:@@ -25,7 +25,7 @@ def one_hot(labels: torch.Tensor,Returns:torch.Tensor: the labels in one hot tensor of shape :math:`(N, C, *)`,- Examples::+ Examples:>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])>>> one_hot(labels, num_classes=3)tensor([[[[1.0000e+00, 1.0000e-06],@@ -38,17 +38,22 @@ def one_hot(labels: torch.Tensor,[1.0000e+00, 1.0000e-06]]]])"""- if not torch.is_tensor(labels):+ if not isinstance(labels, torch.Tensor):raise TypeError("Input labels type is not a torch.Tensor. Got {}".format(type(labels)))+if not labels.dtype == torch.int64:raise ValueError("labels must be of the same dtype torch.int64. Got: {}" .format(labels.dtype))+if num_classes < 1:raise ValueError("The number of classes must be bigger than one."" Got: {}".format(num_classes))+shape = labels.shape- one_hot = torch.zeros(shape[0], num_classes, *shape[1:],- device=device, dtype=dtype)+ one_hot = torch.zeros(+ (shape[0], num_classes) + shape[1:], device=device, dtype=dtype+ )+return one_hot.scatter_(1, labels.unsqueeze(1), 1.0) + epsdiff --git a/test/test_losses.py b/test/test_losses.pyindex db3ff7687..fac180898 100644--- a/test/test_losses.py+++ b/test/test_losses.py@@ -89,9 +89,9 @@ class TestBinaryFocalLossWithLogits:class TestFocalLoss:- def test_smoke_none(self, device):+ def test_smoke_none(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -99,9 +99,9 @@ class TestFocalLoss:logits, labels, alpha=0.5, gamma=2.0, reduction="none").shape == (2, 3, 2)- def test_smoke_sum(self, device):+ def test_smoke_sum(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -111,9 +111,9 @@ class TestFocalLoss:).shape == ())- def test_smoke_mean(self, device):+ def test_smoke_mean(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -123,9 +123,9 @@ class TestFocalLoss:).shape == ())- def test_smoke_mean_flat(self, device):+ def test_smoke_mean_flat(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes).to(device)+ logits = torch.rand(2, num_classes, device=device, dtype=dtype)labels = torch.rand(2) * num_classeslabels = labels.to(device).long()assert (@@ -134,14 +134,10 @@ class TestFocalLoss:).shape == ())- # TODO: implement me- def test_jit(self, device):- pass-- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):num_classes = 3alpha, gamma = 0.5, 2.0 # for focal loss- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -152,37 +148,61 @@ class TestFocalLoss:raise_exception=True,)+ def test_jit(self, device, dtype):+ num_classes = 3+ params = (0.5, 2.0)+ logits = torch.rand(2, num_classes, device=device, dtype=dtype)+ labels = torch.rand(2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.focal_loss+ op_script = torch.jit.script(op)++ actual = op_script(logits, labels, *params)+ expected = op(logits, labels, *params)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ num_classes = 3+ params = (0.5, 2.0)+ logits = torch.rand(2, num_classes, device=device, dtype=dtype)+ labels = torch.rand(2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.focal_loss+ op_module = kornia.losses.FocalLoss(*params)++ actual = op_module(logits, labels)+ expected = op(logits, labels, *params)+ assert_allclose(actual, expected)+class TestTverskyLoss:- def test_smoke(self, device):+ def test_smoke(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)- loss = criterion(logits, labels)+ assert criterion(logits, labels) is not None- def test_all_zeros(self, device):+ def test_all_zeros(self, device, dtype):num_classes = 3- logits = torch.zeros(2, num_classes, 1, 2).to(device)+ logits = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)logits[:, 0] = 10.0logits[:, 1] = 1.0logits[:, 2] = 1.0- labels = torch.zeros(2, 1, 2, dtype=torch.int64).to(device)+ labels = torch.zeros(2, 1, 2, device=device, dtype=torch.int64)criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)loss = criterion(logits, labels)- assert pytest.approx(loss.item(), 0.0)+ assert_allclose(loss, torch.zeros_like(loss), atol=1e-3, rtol=1e-3)- # TODO: implement me- def test_jit(self, device):- pass-- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):num_classes = 3alpha, beta = 0.5, 0.5 # for tversky loss- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -193,36 +213,60 @@ class TestTverskyLoss:raise_exception=True,)+ def test_jit(self, device, dtype):+ num_classes = 3+ params = (0.5, 0.05)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.tversky_loss+ op_script = torch.jit.script(op)++ actual = op_script(logits, labels, *params)+ expected = op(logits, labels, *params)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ num_classes = 3+ params = (0.5, 0.5)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 3, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.tversky_loss+ op_module = kornia.losses.TverskyLoss(*params)++ actual = op_module(logits, labels)+ expected = op(logits, labels, *params)+ assert_allclose(actual, expected)+class TestDiceLoss:- def test_smoke(self, device):+ def test_smoke(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()criterion = kornia.losses.DiceLoss()- loss = criterion(logits, labels)+ assert criterion(logits, labels) is not None- def test_all_zeros(self, device):+ def test_all_zeros(self, device, dtype):num_classes = 3- logits = torch.zeros(2, num_classes, 1, 2).to(device)+ logits = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)logits[:, 0] = 10.0logits[:, 1] = 1.0logits[:, 2] = 1.0- labels = torch.zeros(2, 1, 2, dtype=torch.int64).to(device)+ labels = torch.zeros(2, 1, 2, device=device, dtype=torch.int64)criterion = kornia.losses.DiceLoss()loss = criterion(logits, labels)- assert pytest.approx(loss.item(), 0.0)-- # TODO: implement me- def test_jit(self, device):- pass+ assert_allclose(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):num_classes = 3- logits = torch.rand(2, num_classes, 3, 2).to(device)+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)labels = torch.rand(2, 3, 2) * num_classeslabels = labels.to(device).long()@@ -231,27 +275,59 @@ class TestDiceLoss:kornia.losses.dice_loss, (logits, labels), raise_exception=True)+ def test_jit(self, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.dice_loss+ op_script = torch.jit.script(op)++ assert_allclose(op(logits, labels), op_script(logits, labels))++ def test_module(self, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)+ labels = torch.rand(2, 1, 2) * num_classes+ labels = labels.to(device).long()++ op = kornia.losses.dice_loss+ op_module = kornia.losses.DiceLoss()++ assert_allclose(op(logits, labels), op_module(logits, labels))+class TestDepthSmoothnessLoss:@pytest.mark.parametrize("data_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])- def test_smoke(self, device, data_shape):- image = torch.rand(data_shape).to(device)- depth = torch.rand(data_shape).to(device)+ def test_smoke(self, device, dtype, data_shape):+ image = torch.rand(data_shape, device=device, dtype=dtype)+ depth = torch.rand(data_shape, device=device, dtype=dtype)criterion = kornia.losses.InverseDepthSmoothnessLoss()loss = criterion(depth, image)- # TODO: implement me- def test_1(self, device):- pass+ def test_jit(self, device, dtype):+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)+ depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- # TODO: implement me- def test_jit(self, device):- pass+ op = kornia.losses.inverse_depth_smoothness_loss+ op_script = torch.jit.script(op)- def test_gradcheck(self, device):- image = torch.rand(1, 1, 10, 16).to(device)- depth = torch.rand(1, 1, 10, 16).to(device)+ assert_allclose(op(image, depth), op_script(image, depth))++ def test_module(self, device, dtype):+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)+ depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)++ op = kornia.losses.inverse_depth_smoothness_loss+ op_module = kornia.losses.InverseDepthSmoothnessLoss()++ assert_allclose(op(image, depth), op_module(image, depth))++ def test_gradcheck(self, device, dtype):+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)+ depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)depth = utils.tensor_to_gradcheck_var(depth) # to varimage = utils.tensor_to_gradcheck_var(image) # to varassert gradcheck(@@ -263,32 +339,36 @@ class TestDepthSmoothnessLoss:class TestSSIMLoss:- def test_ssim_equal_none(self, device):+ def test_ssim_equal_none(self, device, dtype):# input data- img1 = torch.rand(1, 1, 10, 16).to(device)- img2 = torch.rand(1, 1, 10, 16).to(device)+ img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)ssim1 = kornia.ssim(img1, img1, window_size=5, reduction="none")ssim2 = kornia.ssim(img2, img2, window_size=5, reduction="none")- assert_allclose(ssim1, torch.zeros_like(img1))- assert_allclose(ssim2, torch.zeros_like(img2))+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)+ assert_allclose(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("reduction_type", ["mean", "sum"])@pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])- def test_ssim(self, device, batch_shape, window_size, reduction_type):+ def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):# input data- img = torch.rand(batch_shape).to(device)+ img = torch.rand(batch_shape, device=device, dtype=dtype)ssim = kornia.losses.SSIM(window_size, reduction_type)- assert_allclose(ssim(img, img).item(), 0.0)+ loss = ssim(img, img)- def test_gradcheck(self, device):+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(loss.item(), 0.0, rtol=tol_val, atol=tol_val)++ def test_gradcheck(self, device, dtype):# input datawindow_size = 3- img1 = torch.rand(1, 1, 10, 16).to(device)- img2 = torch.rand(1, 1, 10, 16).to(device)+ img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)# evaluate function gradientimg1 = utils.tensor_to_gradcheck_var(img1) # to var@@ -379,20 +459,20 @@ class TestDivergenceLoss:assert gradcheck(kornia.losses.js_div_loss_2d, (input, target),raise_exception=True)- def test_jit_trace_kl(self, device, dtype):+ def test_jit_kl(self, device, dtype):input = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)target = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)args = (input, target)op = kornia.losses.kl_div_loss_2d- op_jit = torch.jit.trace(op, args)+ op_jit = torch.jit.script(op, args)assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)- def test_jit_trace_js(self, device, dtype):+ def test_jit_js(self, device, dtype):input = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)target = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)args = (input, target)op = kornia.losses.js_div_loss_2d- op_jit = torch.jit.trace(op, args)+ op_jit = torch.jit.script(op, args)assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)