🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(losses,metrics): Convention blocks and pins for image quality and regression (batch 12a) (#5566)
Dmytro Mishkin6d579a720bd4
diff --git a/changelog.d/5566.added.md b/changelog.d/5566.added.mdnew file mode 100644index 000000000..b436c3dc8--- /dev/null+++ b/changelog.d/5566.added.md@@ -0,0 +1 @@+Convention blocks for the image-quality and regression losses and metrics (`ssim`, `ssim3d`, `psnr`, the SSIM / MS-SSIM / PSNR losses, the Charbonnier / Cauchy / Geman–McClure / Welsch losses, total variation, inverse-depth smoothness and the KL / JS divergences), with `test_convention_*` pins and a new "Losses and metrics" section on the conventions page.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex dd18e3b4b..ad6908eed 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -730,6 +730,134 @@ The edge-preserving filters, the sharpening and the blur pools against their refsamples differently: it zero-pads and keeps every second pixel from index 0, :math:`\lceil H / 2 \rceil` rows,where ``pyrdown`` reflects the border and interpolates between pixels, :math:`\lfloor H / 2 \rfloor` rows.+.. _losses-metrics-conventions:++Losses and metrics+------------------++:doc:`kornia.losses </losses>` and :doc:`kornia.metrics </metrics>` take the prediction first and the target second,+as torch's losses do. The order does not change the value of the symmetric functions, among them SSIM, MS-SSIM, PSNR,+the robust losses and the Jensen-Shannon divergence, but it does for others: :func:`~kornia.losses.kl_div_loss_2d` takes+``pred`` first and returns :math:`\mathrm{KL}(\text{target} \,\|\, \text{pred})`, and+:func:`~kornia.losses.inverse_depth_smoothness_loss` takes the inverse depth it penalises first and the image that+weights it second.++What the families take:++- :func:`~kornia.metrics.ssim`, :func:`~kornia.metrics.ssim3d`, :func:`~kornia.metrics.psnr`, the SSIM losses and+ :class:`~kornia.losses.MS_SSIMLoss` compare images with values in ``[0, L]``, where ``L`` is the data range:+ ``max_val`` everywhere except in :class:`~kornia.losses.MS_SSIMLoss`, which calls it ``data_range`` as scikit-image,+ pytorch-msssim and torchmetrics do. ``L`` sets the SSIM constants :math:`C_1 = (0.01 L)^2` and+ :math:`C_2 = (0.03 L)^2` and the PSNR peak :math:`\text{MAX}_I`. Pixel values are never rescaled, so images in+ ``[0, 255]`` need ``max_val=255.0`` or ``data_range=255.0``. The default is ``1.0`` (``psnr``, ``psnr_loss`` and+ ``PSNRLoss`` have none), where pytorch-msssim defaults to 255.+- The robust losses take two tensors of the same, arbitrary shape; the residual is in the units of the data.+- :func:`~kornia.losses.total_variation` takes one image ``(*, H, W)``.+- :func:`~kornia.losses.kl_div_loss_2d` and :func:`~kornia.losses.js_div_loss_2d` take probabilities: every+ ``(b, n)`` slice of a ``(B, N, H, W)`` input is a distribution over ``H x W``.+- The losses on the segmentation page take raw logits (see `Dense-prediction losses`_) and+ :class:`~kornia.losses.HausdorffERLoss` takes probabilities; the mutual-information losses take intensities of any+ range, which they normalise per signal: per channel of each sample for an image batch.++Where a function takes ``reduction``, the names are torch's: ``'none'``, ``'mean'`` and ``'sum'``. What is averaged or+added and the default differ between families, so each Convention block states both; the table lists the defaults. A+string outside a function's vocabulary raises, ``BaseError`` from the robust losses and+:func:`~kornia.losses.total_variation` and ``NotImplementedError`` from the others.++.. list-table::+ :header-rows: 1++ * - functions+ - default ``reduction``+ - default output+ * - :func:`~kornia.losses.charbonnier_loss`, :func:`~kornia.losses.cauchy_loss`,+ :func:`~kornia.losses.geman_mcclure_loss`, :func:`~kornia.losses.welsch_loss`,+ :func:`~kornia.losses.focal_loss`, :func:`~kornia.losses.binary_focal_loss_with_logits`+ - ``'none'``+ - one value per element, in the shape of the prediction+ * - :func:`~kornia.losses.ssim_loss`, :func:`~kornia.losses.ssim3d_loss`, :class:`~kornia.losses.MS_SSIMLoss`,+ :func:`~kornia.losses.kl_div_loss_2d`, :func:`~kornia.losses.js_div_loss_2d`,+ :class:`~kornia.losses.HausdorffERLoss`, :class:`~kornia.losses.HausdorffERLoss3D`,+ :func:`~kornia.metrics.aepe`, :func:`~kornia.metrics.mean_absolute_disparity_error` and the other disparity+ metrics+ - ``'mean'``+ - a scalar+ * - :func:`~kornia.losses.total_variation`+ - ``'sum'``, with ``'mean'`` the only alternative+ - one value per leading index, ``(*,)``: ``(B, C)`` for an image batch+ * - :func:`~kornia.losses.dice_loss`, :func:`~kornia.losses.tversky_loss`, :func:`~kornia.losses.lovasz_hinge_loss`,+ :func:`~kornia.losses.lovasz_softmax_loss`, :func:`~kornia.metrics.psnr`, :func:`~kornia.losses.psnr_loss`,+ :func:`~kornia.losses.inverse_depth_smoothness_loss`+ - no ``reduction``+ - a scalar+ * - ``mutual_information_loss`` and the other mutual-information losses+ - no ``reduction``+ - one value per signal: ``(B, C)`` for an image batch in the 2-D and 3-D variants+ * - :func:`~kornia.metrics.ssim`, :func:`~kornia.metrics.ssim3d` and the other metrics+ - no ``reduction``+ - stated by each function++The modules take the ``reduction`` of their functions, except :class:`~kornia.losses.TotalVariation`, which has none+and always sums.++Porting from other libraries:++- ``ssim(x, y, 11, max_val=L, eps=0.0, padding='valid').mean()`` for one image matches scikit-image's+ ``structural_similarity(x, y, gaussian_weights=True, sigma=1.5, use_sample_covariance=False, data_range=L,+ channel_axis=-1)`` on the ``(H, W, C)`` arrays up to floating-point differences, and over a batch it matches+ pytorch-msssim's ``ssim(x, y, data_range=L)``. Set ``eps=0.0`` to remove Kornia's added denominator term when+ matching these implementations. The default ``eps=1e-12`` can matter: identical black images score about+ ``0.99998889`` at ``L=1.0``, ``0.9`` at ``L=0.1`` and ``0.00089919`` at ``L=0.01``, where the references give 1.+ scikit-image's defaults, a 7 x 7 uniform window with the sample covariance, give another value. torchmetrics'+ ``structural_similarity_index_measure(x, y, data_range=L)`` averages over a reflected ``'same'`` map instead;+ it has no added denominator epsilon and clamps negative variance estimates from roundoff to zero.+- :func:`~kornia.losses.ssim_loss` is the structural dissimilarity ``(1 - SSIM) / 2``, clamped to ``[0, 1]``. The+ ``1 - SSIM`` loss is twice that: ``1 - ssim(x, y, w).mean()`` equals ``2 * ssim_loss(x, y, w)`` wherever the clamp+ does not act. :func:`~kornia.losses.ssim3d_loss` uses the same clamped DSSIM formula for volumes.+- :class:`~kornia.losses.MS_SSIMLoss` filters with one Gaussian per entry of ``sigmas`` at full resolution, the+ approximation of Zhao et al.; pytorch-msssim's ``ms_ssim`` and torchmetrics'+ ``multiscale_structural_similarity_index_measure`` downsample through a dyadic pyramid, so ``1 - ms_ssim(x, y)`` is+ not ``MS_SSIMLoss(alpha=1.0, compensation=1.0)(x, y)``.+- :func:`~kornia.metrics.psnr` of a batch pools one MSE over all its images: it equals scikit-image's+ ``peak_signal_noise_ratio(x, y, data_range=L)`` on the whole batch array and torchmetrics'+ ``peak_signal_noise_ratio(x, y, data_range=L)`` at its default ``dim=None``. The mean of per-image PSNRs is+ scikit-image's value averaged over the images, or torchmetrics' with ``dim=(1, 2, 3)``.+- ``general.lossfun(x - y, alpha, scale)`` of Barron's ``robust_loss_pytorch`` equals the kornia robust loss of+ ``x / scale`` and ``y / scale`` with the same ``alpha``: 1 for :func:`~kornia.losses.charbonnier_loss`, 0 for+ :func:`~kornia.losses.cauchy_loss`, -2 for :func:`~kornia.losses.geman_mcclure_loss` and ``-inf`` for+ :func:`~kornia.losses.welsch_loss`.+- torchmetrics' ``total_variation(img, reduction='none')`` equals ``total_variation(img).sum(-1)`` for a+ ``(B, C, H, W)`` batch. Its ``'mean'`` averages those per-image sums over the batch, where the ``'mean'`` of+ :func:`~kornia.losses.total_variation` averages each difference term over its own count.+- For strictly positive probabilities, ``kl_div_loss_2d(pred, target)`` equals+ ``F.kl_div(pred.log(), target, reduction='batchmean')`` on the ``(B * N, H * W)`` reshape; torch's+ ``reduction='mean'`` divides by every element instead. Kornia defines zero-target cells with finite nonnegative+ predictions as contributing zero, including shared zero cells, where the raw PyTorch recipe returns NaN. Replace+ both arguments with 1 in these cells before taking the logarithm to reproduce Kornia's handling. torchmetrics'+ ``kl_divergence(target, pred)`` on the reshape matches Kornia's value, including shared zeros. For scipy, reshape+ ``pred`` and ``target`` to NumPy arrays ``p`` and ``q`` of shape ``(B, N, H * W)``. Then+ ``scipy.stats.entropy(q, p, axis=-1).mean()`` matches the default KL loss, and+ ``(scipy.spatial.distance.jensenshannon(p, q, axis=-1) ** 2).mean()`` matches+ :func:`~kornia.losses.js_div_loss_2d`, using scipy's default natural logarithm. Without the final ``mean()``, each+ returns ``(B, N)``, matching ``reduction='none'``. SciPy normalises its inputs, so these mappings require each+ spatial slice to sum to one.+- :func:`~kornia.losses.inverse_depth_smoothness_loss` does not normalise the inverse depth, where Monodepth2 divides+ the disparity by its mean plus ``1e-7`` before its smoothness term: pass+ ``idepth / (idepth.mean((2, 3), keepdim=True) + 1e-7)`` to port it, keeping zero inverse depth finite.++Dense-prediction losses+^^^^^^^^^^^^^^^^^^^^^^^++The losses on the :doc:`segmentation page </losses.segmentation>` take raw logits, not probabilities;+:func:`~kornia.losses.focal_loss` documents the multi-class input, with the classes on axis 1 and an integer label map+as the target.++Task metrics+^^^^^^^^^^^^++:func:`~kornia.metrics.confusion_matrix` puts the target class on the rows and the predicted class on the columns, and+:func:`~kornia.metrics.mean_iou` reads its per-class IoU from that matrix.+.. _two-view-conventions:Two-view geometrydiff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.pyindex 9c0aef494..7abc75c6e 100644--- a/kornia/losses/cauchy.py+++ b/kornia/losses/cauchy.py@@ -30,7 +30,7 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none").. math::- \text{WL}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)+ \text{loss}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)Where:- :math:`x` is the prediction.@@ -40,6 +40,10 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")[1] https://arxiv.org/pdf/1701.03077.pdf[2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf+ Convention:+ See the Convention block of :func:`~kornia.losses.charbonnier_loss`; this is Barron's loss with+ :math:`\alpha = 0`.+Args:img1: the predicted torch.Tensor with shape :math:`(*)`.img2: the target torch.Tensor with the same shape as img1.@@ -50,7 +54,7 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")summed.Return:- a scalar with the computed loss.+ the computed loss, with the shape of the inputs for ``reduction='none'`` and a scalar otherwise.Example:>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)@@ -96,7 +100,7 @@ class CauchyLoss(nn.Module):.. math::- \text{WL}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)+ \text{loss}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)Where:- :math:`x` is the prediction.@@ -106,6 +110,9 @@ class CauchyLoss(nn.Module):[1] https://arxiv.org/pdf/1701.03077.pdf[2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf+ Convention:+ See the Convention block of :func:`~kornia.losses.cauchy_loss`.+Args:reduction: Specifies the reduction to apply to theoutput: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reductiondiff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pyindex 3d5e16e35..f64a1d9b4 100644--- a/kornia/losses/charbonnier.py+++ b/kornia/losses/charbonnier.py@@ -31,7 +31,7 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "n.. math::- \text{WL}(x, y) = \sqrt{(x - y)^{2} + 1} - 1+ \text{loss}(x, y) = \sqrt{(x - y)^{2} + 1} - 1Where:- :math:`x` is the prediction.@@ -47,6 +47,21 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "nThis implementation follows the formulation by Barron [1]. Other works utilizea slightly different implementation (see [4]).+ Convention:+ - The robust losses are the general loss of Barron [1] on the residual ``img1 - img2`` at scale+ :math:`c = 1`: :math:`\alpha = 1` here, :math:`\alpha = 0` in :func:`~kornia.losses.cauchy_loss`,+ :math:`\alpha = -2` in :func:`~kornia.losses.geman_mcclure_loss` and :math:`\alpha = -\infty` in+ :func:`~kornia.losses.welsch_loss`.+ - There is no scale argument: :math:`c = 1` is in the units of the data, so the shape of the penalty depends+ on them; for a scale :math:`c`, pass ``img1 / c`` and ``img2 / c``.+ :ref:`Losses and metrics <losses-metrics-conventions>` maps the losses onto Barron's code.+ - The losses are symmetric in ``img1`` and ``img2``, which must have the same shape, without broadcasting,+ and the same device. The default ``reduction='none'`` returns the loss of every element, in the shape of+ the inputs.+ - This loss, :func:`~kornia.losses.cauchy_loss` and :func:`~kornia.losses.geman_mcclure_loss` evaluate+ float16 and bfloat16 inputs in float32, gradients included, and return the input dtype;+ :func:`~kornia.losses.welsch_loss` does not upcast them.+Args:img1: the predicted torch.Tensor with shape :math:`(*)`.img2: the target torch.Tensor with the same shape as img1.@@ -57,7 +72,7 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "nsummed.Return:- a scalar with the computed loss.+ the computed loss, with the shape of the inputs for ``reduction='none'`` and a scalar otherwise.Example:>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)@@ -112,7 +127,7 @@ class CharbonnierLoss(nn.Module):.. math::- \text{WL}(x, y) = \sqrt{(x - y)^{2} + 1} - 1+ \text{loss}(x, y) = \sqrt{(x - y)^{2} + 1} - 1Where:- :math:`x` is the prediction.@@ -128,6 +143,9 @@ class CharbonnierLoss(nn.Module):This implementation follows the formulation by Barron [1]. Other works utilizea slightly different implementation (see [4]).+ Convention:+ See the Convention block of :func:`~kornia.losses.charbonnier_loss`.+Args:reduction: Specifies the reduction to apply to theoutput: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reductiondiff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex 671b5e62d..c601fb4d7 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -41,9 +41,22 @@ def inverse_depth_smoothness_loss(idepth: torch.Tensor, image: torch.Tensor) ->.. 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 \|}+ \text{loss} = \operatorname{mean}_{nij} \left| \partial_x d_{nij} \right|+ e^{-\frac{1}{C} \sum_c \left| \partial_x I_{ncij} \right|}+ + \operatorname{mean}_{nij} \left| \partial_y d_{nij} \right|+ e^{-\frac{1}{C} \sum_c \left| \partial_y I_{ncij} \right|}++ with forward differences :math:`\partial_x` and :math:`\partial_y`, each mean taken over its own differences.++ Convention:+ - ``idepth`` is penalised and ``image`` only sets the weights: a constant inverse depth gives 0 for any image,+ and a constant image gives the plain mean of :math:`|\partial_x d|` plus that of :math:`|\partial_y d|`.+ - The weights use the raw image values, so ``image`` is expected in a unit range: in ``[0, 255]``, a step of+ a few levels already drives its weight to about 0.+ - ``idepth`` is not normalised, so the loss is linear in its scale;+ :ref:`Losses and metrics <losses-metrics-conventions>` shows how to port a normalised smoothness term.+ - Only the rank, :math:`(H, W)`, device and dtype are validated: the channel counts are not, a batch of one+ broadcasts against the other argument, and swapped arguments return a value.Args:idepth: tensor with the inverse depth with shape :math:`(N, 1, H, W)`.@@ -101,9 +114,15 @@ class InverseDepthSmoothnessLoss(nn.Module):.. 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 \|}+ \text{loss} = \operatorname{mean}_{nij} \left| \partial_x d_{nij} \right|+ e^{-\frac{1}{C} \sum_c \left| \partial_x I_{ncij} \right|}+ + \operatorname{mean}_{nij} \left| \partial_y d_{nij} \right|+ e^{-\frac{1}{C} \sum_c \left| \partial_y I_{ncij} \right|}++ with forward differences :math:`\partial_x` and :math:`\partial_y`, each mean taken over its own differences.++ Convention:+ See the Convention block of :func:`~kornia.losses.inverse_depth_smoothness_loss`.Shape:- Inverse Depth: :math:`(N, 1, H, W)`diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.pyindex 791f51b2f..ad9bbd6f3 100644--- a/kornia/losses/divergence.py+++ b/kornia/losses/divergence.py@@ -68,6 +68,13 @@ def _check_heatmaps(pred: torch.Tensor, target: torch.Tensor) -> None:def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:r"""Calculate the Jensen-Shannon divergence loss between heatmaps.+ Convention:+ - The divergence is :math:`\frac{1}{2} \mathrm{KL}(P \,\|\, M) + \frac{1}{2} \mathrm{KL}(Q \,\|\, M)`+ with :math:`M = (P + Q) / 2`, in nats: symmetric in ``pred`` and ``target``, and at most :math:`\ln 2`. The+ inputs and the reductions are those of :func:`~kornia.losses.kl_div_loss_2d`; see its Convention block.+ - A cell that is zero in both inputs contributes zero, including to the gradients. Both inputs must have+ the same shape; unsupported reductions raise ``NotImplementedError``.+Args:pred: the input torch.Tensor with shape :math:`(B, N, H, W)`.target: the target torch.Tensor with shape :math:`(B, N, H, W)`.@@ -91,6 +98,20 @@ def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mdef kl_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:r"""Calculate the Kullback-Leibler divergence loss between heatmaps.+ Convention:+ - ``kl_div_loss_2d(pred, target)`` is :math:`\mathrm{KL}(\text{target} \,\|\, \text{pred})`, the sum of+ ``target * (log(target) - log(pred))`` over :math:`H \times W` for every :math:`(b, n)`: the order of torch's+ ``F.kl_div(pred.log(), target)``. :ref:`Losses and metrics <losses-metrics-conventions>` maps it onto torch,+ scipy and torchmetrics.+ - The inputs are probabilities, each :math:`(b, n)` slice a distribution over :math:`H \times W`. The log is+ taken inside, so log-probabilities give NaN, and nothing is normalised. A zero in ``pred`` where ``target``+ is positive gives ``inf``.+ - ``reduction='none'`` returns :math:`(B, N)`; the default ``'mean'`` averages over the :math:`B N`+ distributions and ``'sum'`` adds them.+ - Both inputs must have the same shape. Unsupported reductions, including torch's ``'batchmean'``, raise+ ``NotImplementedError``. A zero in ``target`` with a finite nonnegative ``pred`` contributes zero to the+ value and gradients, including when both entries are zero.+Args:pred: the input torch.Tensor with shape :math:`(B, N, H, W)`.target: the target torch.Tensor with shape :math:`(B, N, H, W)`.diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.pyindex 3d937fe74..c78c32c2e 100644--- a/kornia/losses/geman_mcclure.py+++ b/kornia/losses/geman_mcclure.py@@ -30,7 +30,7 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =.. math::- \text{WL}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}+ \text{loss}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}Where:- :math:`x` is the prediction.@@ -40,6 +40,10 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =[1] https://arxiv.org/pdf/1701.03077.pdf[2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985+ Convention:+ See the Convention block of :func:`~kornia.losses.charbonnier_loss`; this is Barron's loss with+ :math:`\alpha = -2`.+Args:img1: the predicted torch.Tensor with shape :math:`(*)`.img2: the target torch.Tensor with the same shape as img1.@@ -50,7 +54,7 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =summed.Return:- a scalar with the computed loss.+ the computed loss, with the shape of the inputs for ``reduction='none'`` and a scalar otherwise.Example:>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)@@ -97,7 +101,7 @@ class GemanMcclureLoss(nn.Module):.. math::- \text{WL}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}+ \text{loss}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}Where:- :math:`x` is the prediction.@@ -107,6 +111,9 @@ class GemanMcclureLoss(nn.Module):[1] https://arxiv.org/pdf/1701.03077.pdf[2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985+ Convention:+ See the Convention block of :func:`~kornia.losses.geman_mcclure_loss`.+Args:reduction: Specifies the reduction to apply to theoutput: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reductiondiff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.pyindex 823418367..5fe57d0b7 100644--- a/kornia/losses/ms_ssim.py+++ b/kornia/losses/ms_ssim.py@@ -30,32 +30,51 @@ from torch import nnclass MS_SSIMLoss(nn.Module):r"""Creates a criterion that computes MSSIM + L1 loss.- According to [1], we compute the MS_SSIM + L1 loss as follows:+ We compute the MS_SSIM + L1 loss of [1] as follows:.. math::- \text{loss}(x, y) = \alpha \cdot \mathcal{L_{MSSIM}}(x,y)+(1 - \alpha) \cdot G_\alpha \cdot \mathcal{L_1}(x,y)+ \text{loss}(x, y) = c \cdot \left(\alpha \cdot \mathcal{L_{MSSIM}}(x,y)+ + (1 - \alpha) \cdot G_{\sigma_M} * \mathcal{L_1}(x,y) / L\right)Where:- - :math:`\alpha` is the weight parameter.+ - :math:`\alpha` is the weight parameter ``alpha``, :math:`c` is ``compensation`` and :math:`L` is+ ``data_range``.- :math:`x` and :math:`y` are the reconstructed and true reference images.- :math:`\mathcal{L_{MSSIM}}` is the MS-SSIM loss.- - :math:`G_\alpha` is the sigma values for computing multi-scale SSIM.+ - :math:`G_{\sigma_M}` is the Gaussian of the last entry :math:`\sigma_M` of ``sigmas``, the coarsest scale.- :math:`\mathcal{L_1}` is the L1 loss.Each channel is filtered at every scale. The MS-SSIM of a channel is its luminance at the coarsest scale times itscontrast-structure at every scale, and :math:`\mathcal{L_{MSSIM}}` is one minus the mean of the per-channel- MS-SSIM, as in the reference implementation [2] of [1]. The L1 term is filtered at the coarsest scale and averaged- over the channels.+ MS-SSIM: the formula of the reference implementation [2] of [1]. [2] evaluates it once per patch, at its centre;+ this loss evaluates it at every pixel. The L1 term is filtered at the coarsest scale and averaged over the channels.++ Convention:+ - "Multi-scale" means one Gaussian per entry of ``sigmas``, all at full resolution, as in [1], not the dyadic+ pyramid of Wang et al.; :ref:`Losses and metrics <losses-metrics-conventions>` compares it with pytorch-msssim+ and torchmetrics.+ - The last entry of ``sigmas`` is the coarsest scale, so the order matters: it sets the window,+ ``2 * int(2 * sigmas[-1]) + 1`` taps wide, the luminance term and the Gaussian of the L1 term.+ - The images are zero-padded by ``int(2 * sigmas[-1])`` pixels, 16 at the default, where+ :func:`~kornia.metrics.ssim` reflects, so the loss is biased in a band that wide along every border: the+ zeros attenuate the L1 term there but can raise the MS-SSIM term, so the band scores lower on the whole than+ reflect padding would at the default ``alpha`` and can score higher at a large ``alpha``.+ - ``data_range`` is the ``max_val`` of :func:`~kornia.metrics.ssim`: it sets :math:`C_1` and :math:`C_2` and+ divides the L1 term; pixel values are not rescaled.+ - The defaults follow [3]: ``alpha=0.025``, as in [2], and ``compensation=200``, which neither [1] nor [2]+ applies; [1] sets :math:`\alpha = 0.84`. The default ``reduction='mean'`` averages the :math:`(B, H, W)`+ map, whose channels are already averaged.Reference:[1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11[2]: https://github.com/NVlabs/PL4NN/blob/master/src/loss.py (``MSSSIML1``)+ [3]: https://github.com/psyrocloud/MS-SSIM_L1_LOSSArgs:- sigmas: gaussian sigma values.+ sigmas: the Gaussian sigma of each scale; the last entry is taken as the coarsest.data_range: the range of the images.- K: k values.- alpha : specifies the alpha value+ K: the constants :math:`(k_1, k_2)` of :math:`C_1 = (k_1 L)^2` and :math:`C_2 = (k_2 L)^2`.+ alpha: the weight of the MS-SSIM term; the L1 term gets :math:`1 - \alpha`.compensation: specifies the scaling coefficient.reduction : Specifies the reduction to apply to theoutput: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex 91c4b7cfd..8bb1dfe69 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -32,12 +32,14 @@ def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torc\text{loss} = -\text{psnr(x, y)}- See :meth:`~kornia.losses.psnr` for details abut PSNR.+ Convention:+ - See the Convention block of :func:`~kornia.metrics.psnr`: the MSE is pooled over the batch, and identical+ inputs give ``-inf``.Args:image: the input image with shape :math:`(*)`.target : the labels image with shape :math:`(*)`.- max_val: The maximum value in the image tensor.+ max_val: the data range of the images, :math:`\text{MAX}_I`.Return:the computed loss as a scalar.@@ -60,10 +62,12 @@ class PSNRLoss(nn.Module):\text{loss} = -\text{psnr(x, y)}- See :meth:`~kornia.losses.psnr` for details abut PSNR.+ Convention:+ See the Convention block of :func:`~kornia.metrics.psnr`: the MSE is pooled over the batch, and identical+ inputs give ``-inf``.Args:- max_val: The maximum value in the image tensor.+ max_val: the data range of the images, :math:`\text{MAX}_I`.Shape:- Image: arbitrary dimensional tensor :math:`(*)`.diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.pyindex 7cc56aff5..cc26721e7 100644--- a/kornia/losses/ssim.py+++ b/kornia/losses/ssim.py@@ -40,7 +40,13 @@ def ssim_loss(\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}- See :meth:`~kornia.losses.ssim` for details about SSIM.+ Convention:+ - See the Convention block of :func:`~kornia.metrics.ssim` for the window, the border and ``max_val``.+ - The per-pixel loss is the structural dissimilarity clamped to :math:`[0, 1]`,+ ``clamp((1 - SSIM) / 2, 0, 1)``; :ref:`Losses and metrics <losses-metrics-conventions>` relates it to the+ ``1 - SSIM`` loss. The clamp acts only where roundoff pushes the map outside :math:`[-1, 1]`, as for images+ with a large constant offset.+ - The default ``reduction='mean'`` averages every element; ``'none'`` keeps the shape of the SSIM map.Args:img1: the first input image with shape :math:`(B, C, H, W)`.@@ -91,7 +97,8 @@ class SSIMLoss(nn.Module):\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}- See :meth:`~kornia.losses.ssim_loss` for details about SSIM.+ Convention:+ See the Convention block of :func:`~kornia.losses.ssim_loss`.Args:window_size: the size of the gaussian kernel to smooth the images.diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.pyindex 39310324d..c2730ef64 100644--- a/kornia/losses/ssim3d.py+++ b/kornia/losses/ssim3d.py@@ -34,13 +34,16 @@ def ssim3d_loss() -> torch.Tensor:r"""Compute a loss based on the SSIM measurement.- The loss, or the Structural dissimilarity (DSSIM) is described as:+ The loss is the structural dissimilarity (DSSIM) of each voxel, clamped to :math:`[0, 1]`:.. math::\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}- See :meth:`~kornia.losses.ssim` for details about SSIM.+ Convention:+ - See the Convention block of :func:`~kornia.metrics.ssim3d` for the window, the border and ``max_val``.+ - The default ``reduction='mean'`` averages every element; ``'none'`` keeps the shape of the SSIM map.+ - The per-voxel loss is ``clamp((1 - SSIM) / 2, 0, 1)``, as in :func:`~kornia.losses.ssim_loss`.Args:img1: the first input image with shape :math:`(B, C, D, H, W)`.@@ -85,13 +88,14 @@ def ssim3d_loss(class SSIM3DLoss(nn.Module):r"""Create a criterion that computes a loss based on the SSIM measurement.- The loss, or the Structural dissimilarity (DSSIM) is described as:+ The loss is the structural dissimilarity (DSSIM) of each voxel, clamped to :math:`[0, 1]`:.. math::\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}- See :meth:`~kornia.losses.ssim_loss` for details about SSIM.+ Convention:+ - See the Convention block of :func:`~kornia.losses.ssim3d_loss`.Args:window_size: the size of the gaussian kernel to smooth the images.diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex cf1c88454..ccf89245b 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -26,11 +26,20 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEdef total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:r"""Compute Total Variation according to [1].+ Convention:+ - The anisotropic L1 variation, :math:`\sum |\partial_y I| + \sum |\partial_x I|`, over the last two axes+ only: the output keeps every leading axis, :math:`(B, C)` for an image batch, and the channels are not+ summed.+ - The default ``reduction='sum'`` adds the differences. ``'mean'`` averages each term over its own count,+ :math:`(H - 1) W` vertical and :math:`H (W - 1)` horizontal differences, and adds the two means; it is not+ the sum divided by :math:`H W`. There is no ``'none'``.+ :ref:`Losses and metrics <losses-metrics-conventions>` compares both with torchmetrics.+Args:img: the input image with shape :math:`(*, H, W)`.reduction : Specifies the reduction to apply to the output: ``'mean'`` | ``'sum'``.- ``'mean'``: the sum of the output will be divided by the number of elements- in the output, ``'sum'``: the output will be summed.+ ``'mean'``: each of the vertical and horizontal terms is averaged over its own number of differences,+ ``'sum'``: the differences are summed.Return:a torch.Tensor with shape :math:`(*,)`.@@ -43,8 +52,8 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:.. note::See a working example `here <https://www.kornia.org/tutorials/nbs/total_variation_denoising.html>`__.- Total Variation is formulated with summation, however this is not resolution invariant.- Thus, `reduction='mean'` was added as an optional reduction method.+ Total Variation is formulated with summation, however this is not resolution invariant;+ ``reduction='mean'`` averages instead.Narrow integer inputs are promoted before computing differences to avoid overflow.Reference:@@ -93,6 +102,10 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:class TotalVariation(nn.Module):r"""Compute the Total Variation according to [1].+ Convention:+ See the Convention block of :func:`~kornia.losses.total_variation`. The module has no ``reduction`` and+ always sums.+Shape:- Input: :math:`(*, H, W)`.- Output: :math:`(*,)`.diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.pyindex d49f6b94e..977f0507b 100644--- a/kornia/losses/welsch.py+++ b/kornia/losses/welsch.py@@ -42,6 +42,10 @@ def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")[2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083[3] https://link.springer.com/article/10.1007/BF00054839+ Convention:+ See the Convention block of :func:`~kornia.losses.charbonnier_loss`; this is Barron's loss with+ :math:`\alpha = -\infty`.+Args:img1: the predicted torch.Tensor with shape :math:`(*)`.img2: the target torch.Tensor with the same shape as img1.@@ -52,7 +56,7 @@ def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")summed.Return:- a scalar with the computed loss.+ the computed loss, with the shape of the inputs for ``reduction='none'`` and a scalar otherwise.Example:>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)@@ -109,6 +113,9 @@ class WelschLoss(nn.Module):[2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083[3] https://link.springer.com/article/10.1007/BF00054839+ Convention:+ See the Convention block of :func:`~kornia.losses.welsch_loss`.+Args:reduction: Specifies the reduction to apply to theoutput: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reductiondiff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.pyindex cb3cd6169..9e0f42841 100644--- a/kornia/metrics/psnr.py+++ b/kornia/metrics/psnr.py@@ -22,8 +22,7 @@ from torch.nn.functional import mse_loss as msedef psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:r"""Create a function that calculates the PSNR between 2 images.- PSNR is Peek Signal to Noise Ratio, which is similar to mean squared error.- Given an m x n image, the PSNR is:+ PSNR is the Peak Signal to Noise Ratio. For one m x n image, the PSNR is:.. math::@@ -38,13 +37,24 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tenand :math:`\text{MAX}_I` is the maximum possible input value(e.g for floating point images :math:`\text{MAX}_I=1`).+ Convention:+ - One MSE is pooled over every element, batch and channels included, and the result is a single value: for a+ batch it is the PSNR of the pooled MSE, not the mean of per-image PSNRs, so compute per-image values one+ image at a time. :ref:`Losses and metrics <losses-metrics-conventions>` maps both onto scikit-image and+ torchmetrics.+ - ``max_val`` is :math:`\text{MAX}_I`, the data range of the images (``1.0`` for ``[0, 1]``, ``255.0`` for+ ``[0, 255]``), not the maximum of the tensor; pixel values are not rescaled.+ - ``image`` and ``target`` must have the same shape, without broadcasting; the value is symmetric in them.+ Identical inputs give an MSE of 0 and ``inf``, while a batch with one identical pair stays finite.+ - Integer and bool images are converted to float32 before computing the MSE; pixel values are not rescaled.+Args:image: the input image with arbitrary shape :math:`(*)`.target: the labels image with arbitrary shape :math:`(*)`.- max_val: The maximum value in the input tensor.+ max_val: the data range of the images, :math:`\text{MAX}_I`.Return:- the computed loss as a scalar.+ the PSNR as a scalar... note::Integer and bool images are converted to float32, as in :func:`~kornia.metrics.ssim`, and the two images arediff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex 96ecff5cc..46c828e73 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -57,6 +57,25 @@ def ssim(- :math:`L` is the dynamic range of the pixel-values (typically this is:math:`2^{\#\text{bits per pixel}}-1`).+ Convention:+ - The window is a sampled Gaussian with :math:`\sigma = 1.5` whatever ``window_size``, which sets only the+ number of taps and must be odd.+ - ``padding='same'`` pads with ``'reflect'``, the torch mode that :ref:`Filtering <filtering-conventions>` maps+ onto OpenCV and scipy, and keeps :math:`(H, W)`; ``'valid'`` drops ``window_size // 2`` pixels on every side+ and equals the ``'same'`` map cropped. Sizes are not checked: ``'same'`` needs ``H`` and ``W`` larger than+ ``window_size // 2``.+ - ``max_val`` is the data range :math:`L`, a Python ``float``: :math:`c_1 = (0.01 L)^2` and+ :math:`c_2 = (0.03 L)^2`. Pixel values are not rescaled, so images in ``[0, 255]`` need ``max_val=255.0``.+ ``eps`` is added to the denominator: two identical flat images of value :math:`\mu` score+ :math:`1 - \text{eps} / ((2\mu^2 + c_1)\, c_2 + \text{eps})`. With the default ``eps=1e-12``, black+ images score about ``0.99998889`` at ``max_val=1.0``; the bias grows to ``0.1`` at ``max_val=0.1``.+ Use ``eps=0.0`` to omit this denominator term when matching reference implementations.+ - The map is not reduced: one value per pixel, channel and sample, symmetric in ``img1`` and ``img2``, in+ :math:`[-1, 1]` in exact arithmetic and negative for anti-correlated content.+ :ref:`Losses and metrics <losses-metrics-conventions>` maps its mean onto scikit-image, pytorch-msssim and+ torchmetrics.+ - ``padding`` accepts ``'same'`` and ``'valid'`` case-insensitively; unsupported values raise ``BaseError``.+Args:img1: the first input image with shape :math:`(B, C, H, W)`.img2: the second input image with shape :math:`(B, C, H, W)`.@@ -67,7 +86,8 @@ def ssim(area to compute SSIM to match the MATLAB implementation of original SSIM paper.Returns:- The ssim index map with shape :math:`(B, C, H, W)`.+ The ssim index map with shape :math:`(B, C, H, W)`, or :math:`(B, C, H - 2p, W - 2p)` with+ ``p = window_size // 2`` under ``padding='valid'``.Note:Integer images are converted to float32 before computing the local moments.@@ -189,6 +209,9 @@ class SSIM(nn.Module):- :math:`L` is the dynamic range of the pixel-values (typically this is:math:`2^{\#\text{bits per pixel}}-1`).+ Convention:+ See the Convention block of :func:`~kornia.metrics.ssim`.+Args:window_size: the size of the gaussian kernel to smooth the images.max_val: the dynamic range of the images.@@ -199,7 +222,8 @@ class SSIM(nn.Module):Shape:- Input: :math:`(B, C, H, W)`.- Target :math:`(B, C, H, W)`.- - Output: :math:`(B, C, H, W)`.+ - Output: :math:`(B, C, H, W)`, or :math:`(B, C, H - 2p, W - 2p)` with ``p = window_size // 2`` under+ ``padding='valid'``.Examples:>>> input1 = torch.rand(1, 4, 5, 5)@@ -224,7 +248,7 @@ class SSIM(nn.Module):img2: Second image tensor with the same shape as ``img1``.Returns:- Tensor with shape :math:`(B, C, H, W)` containing local structural+ Tensor with shape :math:`(B, C, H, W)`, cropped under ``padding='valid'``, containing local structuralsimilarity values for each channel and spatial location."""return ssim(img1, img2, self.window_size, self.max_val, self.eps, self.padding)diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex a9ff215da..c0b2c5cf1 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -66,6 +66,13 @@ def ssim3d(- :math:`L` is the dynamic range of the pixel-values (typically this is:math:`2^{\#\text{bits per pixel}}-1`).+ Convention:+ - See the Convention block of :func:`~kornia.metrics.ssim` for the window, reflected border, ``padding`` and+ ``max_val``. ``ssim3d`` applies them to :math:`(D, H, W)` with an isotropic Gaussian window, and ``'valid'``+ crops every axis. A volume of identical slices reproduces the 2-D map up to floating-point roundoff.+ - The Gaussian window uses the computation dtype of the inputs; integer and half-precision inputs are+ evaluated in float32.+Args:img1: the first input image with shape :math:`(B, C, D, H, W)`.img2: the second input image with shape :math:`(B, C, D, H, W)`.@@ -76,7 +83,8 @@ def ssim3d(area to compute SSIM to match the MATLAB implementation of original SSIM paper.Returns:- The ssim index map with shape :math:`(B, C, D, H, W)`.+ The ssim index map with shape :math:`(B, C, D, H, W)`, or :math:`(B, C, D - 2p, H - 2p, W - 2p)` with+ ``p = window_size // 2`` under ``padding='valid'``.Note:The volume is reflected at its faces for ``padding='same'``, as :func:`kornia.metrics.ssim` does for@@ -193,6 +201,9 @@ class SSIM3D(nn.Module):- :math:`L` is the dynamic range of the pixel-values (typically this is:math:`2^{\#\text{bits per pixel}}-1`).+ Convention:+ See the Convention block of :func:`~kornia.metrics.ssim3d`.+Args:window_size: the size of the gaussian kernel to smooth the images.max_val: the dynamic range of the images.@@ -203,7 +214,8 @@ class SSIM3D(nn.Module):Shape:- Input: :math:`(B, C, D, H, W)`.- Target :math:`(B, C, D, H, W)`.- - Output: :math:`(B, C, D, H, W)`.+ - Output: :math:`(B, C, D, H, W)`, or :math:`(B, C, D - 2p, H - 2p, W - 2p)` with ``p = window_size // 2``+ under ``padding='valid'``.Examples:>>> input1 = torch.rand(1, 4, 5, 5, 5)@@ -228,7 +240,7 @@ class SSIM3D(nn.Module):img2: Second volume tensor with the same shape as ``img1``.Returns:- Tensor with shape :math:`(B, C, D, H, W)` containing local+ Tensor with shape :math:`(B, C, D, H, W)`, cropped under ``padding='valid'``, containing localstructural similarity values across depth, height, and width."""return ssim3d(img1, img2, self.window_size, self.max_val, self.eps, self.padding)diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex 772440e8c..bc3a12999 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -207,7 +207,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(),*_audited("tests/losses/test_total_variation.py",- 148,+ 149,"torch.rand",3,("tests/losses/test_total_variation.py::TestTotalVariation::test_tv_shapes",),diff --git a/tests/losses/test_charbonnier.py b/tests/losses/test_charbonnier.pyindex 5e320416e..a63adcb01 100644--- a/tests/losses/test_charbonnier.py+++ b/tests/losses/test_charbonnier.py@@ -200,3 +200,78 @@ class TestCharbonnierLoss(BaseTester):expected = (torch.ones_like(img1, device=device, dtype=dtype) * 0.41421356237).sum()self.assert_close(actual, expected)+++class TestConventionsRobustLosses(BaseTester):+ @pytest.mark.parametrize(+ "loss_fn, module, expected",+ [+ pytest.param(+ kornia.losses.charbonnier_loss,+ kornia.losses.CharbonnierLoss,+ [0.0, 0.1180339887498949, 1.2360679774997898],+ id="charbonnier-alpha_1",+ ),+ pytest.param(+ kornia.losses.cauchy_loss,+ kornia.losses.CauchyLoss,+ [0.0, 0.11778303565638346, 1.0986122886681098],+ id="cauchy-alpha_0",+ ),+ pytest.param(+ kornia.losses.geman_mcclure_loss,+ kornia.losses.GemanMcclureLoss,+ [0.0, 0.11764705882352944, 1.0],+ id="geman_mcclure-alpha_-2",+ ),+ pytest.param(+ kornia.losses.welsch_loss,+ kornia.losses.WelschLoss,+ [0.0, 0.1175030974154046, 0.8646647167633873],+ id="welsch-alpha_-inf",+ ),+ ],+ )+ def test_convention_robust_loss_is_barron_loss_at_unit_scale(self, loss_fn, module, expected, device, dtype):+ # Each loss is Barron's general loss rho(img1 - img2, alpha, c) at the fixed scale c = 1: Charbonnier alpha = 1,+ # Cauchy alpha = 0, Geman-McClure alpha = -2, Welsch alpha = -inf. It is even in the residual, so symmetric in+ # (img1, img2), and the default reduction 'none' keeps the input shape.+ # Snippet used to generate expected (robust_loss_pytorch 0.0.2, git jonbarron/robust_loss_pytorch@0c25c59):+ # general.lossfun(torch.tensor([0.0, 0.5, 2.0], dtype=torch.float64), torch.tensor(alpha), torch.tensor(1.0))+ img2 = torch.tensor([[0.25, -1.0, 1.5], [0.75, 0.125, -0.5]], device=device, dtype=dtype)+ residual = torch.tensor([[0.0, 0.5, -2.0], [-0.5, 2.0, 0.0]], device=device, dtype=dtype)+ img1 = img2 + residual+ values = torch.tensor(expected, device=device, dtype=dtype)+ expected_map = torch.stack([values, values[[1, 2, 0]]])+ out = loss_fn(img1, img2)+ assert out.shape == (2, 3)+ self.assert_close(out, expected_map)+ self.assert_close(loss_fn(img2, img1), expected_map)+ self.assert_close(module()(img1, img2), expected_map)++ @pytest.mark.parametrize(+ "loss_fn",+ [+ kornia.losses.charbonnier_loss,+ kornia.losses.cauchy_loss,+ kornia.losses.geman_mcclure_loss,+ kornia.losses.welsch_loss,+ ],+ ids=["charbonnier", "cauchy", "geman_mcclure", "welsch"],+ )+ def test_convention_robust_loss_half_precision_compute_dtype(self, loss_fn, device, dtype):+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("only half-precision inputs can be evaluated in another dtype")+ # Charbonnier, Cauchy and Geman-McClure evaluate half-precision inputs in float32 and round once; their+ # gradients are pinned in test_robust.py. Welsch does not upcast, so in eager mode some of these 641 values+ # round differently from the float32 evaluation (46 to 68 on arm64 CPU and MPS). This pin runs eagerly:+ # inductor keeps fused intermediates in float32, and compiled Welsch matches the float32 evaluation on the+ # same grid (torch 2.14, CPU and MPS). All four return the input dtype.+ residual = torch.linspace(-8.0, 8.0, 641, device=device, dtype=dtype)+ out = loss_fn(residual, torch.zeros_like(residual))+ assert out.dtype == dtype+ in_float32 = loss_fn(residual.float(), torch.zeros_like(residual, dtype=torch.float32)).to(dtype)+ if loss_fn is kornia.losses.welsch_loss:+ assert not torch.equal(out, in_float32)+ else:+ self.assert_close(out, in_float32, rtol=0, atol=0)diff --git a/tests/losses/test_depth_smoothness.py b/tests/losses/test_depth_smoothness.pyindex 31f1ff28e..2774e129f 100644--- a/tests/losses/test_depth_smoothness.py+++ b/tests/losses/test_depth_smoothness.py@@ -15,6 +15,8 @@# limitations under the License.#+import math+import pytestimport torch@@ -85,3 +87,45 @@ class TestDepthSmoothnessLoss(BaseTester):image = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)depth = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)self.gradcheck(kornia.losses.inverse_depth_smoothness_loss, (depth, image))+++class TestConventionsInverseDepthSmoothness(BaseTester):+ @staticmethod+ def _steps(device, dtype):+ # H = 4, W = 6. The image steps once, between columns 1 and 2, by 0.5, 1.0 and 1.5 in its three channels+ # (channel mean 1.0). The inverse depth steps by 1 on that image edge and by 0.5 between columns 3 and 4, where+ # the image is flat, and rises by 0.25 per row; sample 1 doubles sample 0.+ rows = torch.arange(4.0).view(4, 1)+ cols = torch.arange(6.0).view(1, 6)+ idepth = (1.0 * (cols >= 2) + 0.5 * (cols >= 4) + 0.25 * rows).expand(1, 1, 4, 6)+ idepth = torch.cat([idepth, 2 * idepth])+ image = (torch.tensor([0.5, 1.0, 1.5]).view(3, 1, 1) * (cols >= 2)).expand(2, 3, 4, 6)+ return idepth.to(device, dtype), image.to(device, dtype)++ def test_convention_inverse_depth_smoothness_weights_by_the_channel_mean_image_gradient(self, device, dtype):+ # loss = mean(|dx d| exp(-mean_c |dx I|)) + mean(|dy d| exp(-mean_c |dy I|)) with forward differences, the+ # weight of each difference taken from the image difference at the same place, each mean over its own count and+ # over the batch. Per row of sample 0 the five x-differences cost exp(-1) on the image edge and 0.5 on the flat+ # step, and every y-difference 0.25 under a weight of 1: (exp(-1) + 0.5) / 5 + 0.25. Sample 1 costs twice that:+ # the inverse depth is not normalised.+ idepth, image = self._steps(device, dtype)+ expected = torch.tensor(1.5 * ((math.exp(-1.0) + 0.5) / 5 + 0.25), device=device, dtype=dtype)+ self.assert_close(kornia.losses.inverse_depth_smoothness_loss(idepth, image), expected)+ self.assert_close(kornia.losses.InverseDepthSmoothnessLoss()(idepth, image), expected)++ def test_convention_inverse_depth_smoothness_penalises_the_first_argument(self, device, dtype):+ # The first argument (the inverse depth) is penalised and the second (the image) only sets the weights: a+ # constant inverse depth costs 0 whatever the image, and a constant image leaves the plain mean |grad d|. The+ # channel counts (N, 1, H, W) and (N, 3, H, W) are not validated, so swapped arguments also return a value, and+ # neither is the batch size: a batch of one broadcasts against the other argument.+ idepth, image = self._steps(device, dtype)+ loss = kornia.losses.inverse_depth_smoothness_loss+ self.assert_close(loss(idepth[:1], image), loss(idepth[:1].expand_as(idepth), image))+ zero = torch.zeros((), device=device, dtype=dtype)+ self.assert_close(kornia.losses.inverse_depth_smoothness_loss(torch.ones_like(idepth), image), zero)+ flat = torch.ones_like(image)+ expected = torch.tensor(1.5 * ((1.0 + 0.5) / 5 + 0.25), device=device, dtype=dtype)+ self.assert_close(kornia.losses.inverse_depth_smoothness_loss(idepth, flat), expected)+ swapped = kornia.losses.inverse_depth_smoothness_loss(image, idepth)+ assert torch.isfinite(swapped)+ assert (swapped - kornia.losses.inverse_depth_smoothness_loss(idepth, image)).abs() > 0.1diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.pyindex 08dd26f8c..acd812d4e 100644--- a/tests/losses/test_divergence.py+++ b/tests/losses/test_divergence.py@@ -213,3 +213,133 @@ class TestDivergenceLoss(BaseTester):actual = loss(pred, target, reduction="none")self.assert_close(actual[0], loss(q, p, reduction="none")[0])assert torch.isnan(actual[1:]).all()+++class TestConventionsDivergence(BaseTester):+ """Pins for the direction, input form and reductions of the 2-D divergences, and validation (#5535, #5554)."""++ # Two distributions over a 2 x 3 grid with KL(P || Q) != KL(Q || P); every entry is exact in every dtype.+ _P = (12.0 / 16, 2.0 / 16, 1.0 / 16, 0.5 / 16, 0.25 / 16, 0.25 / 16)+ _Q = (2.0 / 16, 2.0 / 16, 2.0 / 16, 2.0 / 16, 4.0 / 16, 4.0 / 16)++ def _distributions(self, device, dtype):+ p = torch.tensor(self._P, device=device, dtype=dtype).view(1, 1, 2, 3)+ q = torch.tensor(self._Q, device=device, dtype=dtype).view(1, 1, 2, 3)+ return p, q++ @staticmethod+ def _batch(device, dtype):+ # (B, N, H, W) = (2, 3, 4, 6): every (b, n) slice is a different distribution over H x W+ g = torch.Generator().manual_seed(0)+ pred = torch.softmax(torch.randn(2, 3, 24, generator=g, dtype=torch.float64), -1).view(2, 3, 4, 6)+ target = torch.softmax(torch.randn(2, 3, 24, generator=g, dtype=torch.float64), -1).view(2, 3, 4, 6)+ return pred, target++ def test_convention_kl_div_loss_2d_is_kl_of_target_from_pred(self, device, dtype):+ # kl_div_loss_2d(pred, target) = KL(target || pred) = sum target * (log target - log pred) over H x W, the order+ # of torch's F.kl_div(pred.log(), target); scipy.stats.entropy(target.flatten(), pred.flatten()) gives the same+ # number. Inputs are probabilities: the log is taken inside.+ pred, target = self._distributions(device, dtype)+ kl_target_pred = sum(q * math.log(q / p) for p, q in zip(self._P, self._Q)) # 1.4223+ kl_pred_target = sum(p * math.log(p / q) for p, q in zip(self._P, self._Q)) # 1.1705+ assert abs(kl_target_pred - kl_pred_target) > 0.2+ expected = torch.tensor(kl_target_pred, device=device, dtype=dtype)+ self.assert_close(kornia.losses.kl_div_loss_2d(pred, target), expected)+ # A zero in target where pred > 0 adds nothing (0 log 0 = 0): 1/4 ln 2 + 3/4 ln 3 for this dyadic pair.+ full = torch.tensor([0.125, 0.125, 0.25, 0.25, 0.125, 0.125], device=device, dtype=dtype).view(1, 1, 2, 3)+ sparse = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)+ expected = torch.tensor(0.25 * math.log(2.0) + 0.75 * math.log(3.0), device=device, dtype=dtype)+ self.assert_close(kornia.losses.kl_div_loss_2d(full, sparse), expected)++ def test_convention_kl_div_loss_2d_reduces_over_batch_and_channels(self, device, dtype):+ # Each (b, n) slice is one distribution over H x W: 'none' returns (B, N), the default 'mean' averages over the+ # B N slices (torch's 'batchmean' on the (B N, H W) reshape) and 'sum' adds them.+ pred, target = self._batch(device, dtype)+ expected = (target * (target.log() - pred.log())).sum((-2, -1))+ pred, target, expected = pred.to(device, dtype), target.to(device, dtype), expected.to(device, dtype)+ none = kornia.losses.kl_div_loss_2d(pred, target, reduction="none")+ assert none.shape == (2, 3)+ self.assert_close(none, expected)+ self.assert_close(kornia.losses.kl_div_loss_2d(pred, target), expected.mean())+ # The direct PyTorch port is valid on this strictly positive support.+ torch_loss = torch.nn.functional.kl_div(pred.reshape(6, -1).log(), target.reshape(6, -1), reduction="batchmean")+ self.assert_close(kornia.losses.kl_div_loss_2d(pred, target), torch_loss)+ self.assert_close(kornia.losses.kl_div_loss_2d(pred, target, reduction="sum"), expected.sum())+ # Nothing is normalised: doubling both inputs doubles every slice's value.+ self.assert_close(kornia.losses.kl_div_loss_2d(2 * pred, 2 * target, reduction="none"), 2 * expected)+ # Relabelling check: permuting the channels of both inputs permutes the 'none' output.+ perm = [2, 0, 1]+ self.assert_close(kornia.losses.kl_div_loss_2d(pred[:, perm], target[:, perm], reduction="none"), none[:, perm])++ def test_convention_js_div_loss_2d_is_symmetric_and_at_most_ln_2(self, device, dtype):+ # JS = KL(P || M) / 2 + KL(Q || M) / 2 with M = (P + Q) / 2, in nats: symmetric in its arguments, and ln 2 for+ # distributions with disjoint supports. The default reduction is the mean over the (B, N) slices.+ p, q = self._distributions(device, dtype)+ m = [(a + b) / 2 for a, b in zip(self._P, self._Q)]+ js = 0.5 * sum(a * math.log(a / c) for a, c in zip(self._P, m)) + 0.5 * sum(+ b * math.log(b / c) for b, c in zip(self._Q, m)+ ) # 0.2689+ expected = torch.tensor(js, device=device, dtype=dtype)+ self.assert_close(kornia.losses.js_div_loss_2d(p, q), expected)+ self.assert_close(kornia.losses.js_div_loss_2d(q, p), expected)+ # Disjoint supports attain ln 2, including when both inputs contain an empty cell (#5554).+ left = torch.tensor([0.5, 0.25, 0.25, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)+ right = torch.tensor([0.0, 0.0, 0.0, 0.25, 0.25, 0.5], device=device, dtype=dtype).view(1, 1, 2, 3)+ ln2 = torch.tensor(math.log(2.0), device=device, dtype=dtype)+ self.assert_close(kornia.losses.js_div_loss_2d(left, right), ln2)+ pred, target = self._batch(device, dtype)+ pred, target = pred.to(device, dtype), target.to(device, dtype)+ none = kornia.losses.js_div_loss_2d(pred, target, reduction="none")+ assert none.shape == (2, 3)+ self.assert_close(kornia.losses.js_div_loss_2d(pred, target), none.mean())++ def test_convention_div_loss_2d_rejects_unknown_reduction_5535(self, device, dtype):+ """An unknown reduction, torch's 'batchmean' included, raises NotImplementedError (#5535)."""+ pred, target = self._batch(device, dtype)+ pred, target = pred.to(device, dtype), target.to(device, dtype)+ for loss_fn in (kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d):+ total = loss_fn(pred, target, reduction="sum")+ assert (total - loss_fn(pred, target, reduction="mean")).abs() > 0.1+ for reduction in ("batchmean", "MEAN", None):+ with pytest.raises(NotImplementedError, match="Invalid reduction mode"):+ loss_fn(pred, target, reduction=reduction)++ def test_convention_kl_div_loss_2d_rejects_a_transposed_pred_5535(self, device, dtype):+ """A pred with H and W swapped is rejected instead of reinterpreted in target's layout (#5535)."""+ pred, target = self._batch(device, dtype)+ pred, target = pred.to(device, dtype), target.to(device, dtype)+ transposed = pred.transpose(-2, -1).contiguous()+ assert transposed.shape == (2, 3, 6, 4)+ with pytest.raises(BaseError, match="pred and target shapes must be the same"):+ kornia.losses.kl_div_loss_2d(transposed, target)++ def test_convention_div_loss_2d_empty_cells_contribute_zero_5554(self, device, dtype):+ """A cell that is zero in both pred and target contributes zero (#5554)."""+ p = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)+ q = torch.tensor([0.0, 0.5, 0.25, 0.25, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)+ full = torch.tensor([0.125, 0.125, 0.25, 0.25, 0.125, 0.125], device=device, dtype=dtype).view(1, 1, 2, 3)+ self.assert_close(kornia.losses.kl_div_loss_2d(p, p), p.new_zeros(()))+ self.assert_close(kornia.losses.js_div_loss_2d(p, p), p.new_zeros(()))+ m = (p + q) / 2+ expected = 0.5 * (+ (p[p > 0] * (p[p > 0] / m[p > 0]).log()).sum() + (q[q > 0] * (q[q > 0] / m[q > 0]).log()).sum()+ )+ self.assert_close(kornia.losses.js_div_loss_2d(p, q), expected)+ # The sparse PyTorch port must mask zero-target/finite-pred cells before the logarithm. This pair includes+ # shared zeros, a zero target with positive pred, and unequal positive entries.+ pred, target = full.clone(), p.clone()+ pred[..., 0, 0] = 0.0+ pred[..., 1, 2] += 0.125 # keep pred normalised without changing either positive target cell+ empty = (target == 0) & (pred >= 0) & torch.isfinite(pred)+ torch_loss = torch.nn.functional.kl_div(+ pred.masked_fill(empty, 1.0).reshape(1, -1).log(),+ target.masked_fill(empty, 1.0).reshape(1, -1),+ reduction="batchmean",+ )+ expected_kl = p.new_tensor(0.25 * math.log(2.0) + 0.75 * math.log(3.0))+ self.assert_close(torch_loss, expected_kl)+ self.assert_close(kornia.losses.kl_div_loss_2d(pred, target), torch_loss)+ batch = torch.cat([p, full])+ none = kornia.losses.kl_div_loss_2d(batch, batch, reduction="none")+ self.assert_close(none, torch.zeros_like(none))+ self.assert_close(kornia.losses.kl_div_loss_2d(batch, batch), p.new_zeros(()))diff --git a/tests/losses/test_psnr.py b/tests/losses/test_psnr.pyindex b5458db8a..d55f15895 100644--- a/tests/losses/test_psnr.py+++ b/tests/losses/test_psnr.py@@ -15,6 +15,8 @@# limitations under the License.#+import math+import pytestimport torch@@ -89,3 +91,17 @@ class TestPSNRLoss(BaseTester):pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)self.gradcheck(kornia.losses.psnr_loss, (pred, target, 1.0))+++class TestConventionsPSNRLoss(BaseTester):+ def test_convention_psnr_loss_is_minus_psnr(self, device, dtype):+ # psnr_loss is -psnr on the MSE pooled over the batch, PSNRLoss is the same function, and identical images give+ # -inf: here -10 log10(2 / (0.125**2 + 0.375**2)) = -11.0721+ a = torch.zeros(2, 1, 4, 6, device=device, dtype=dtype)+ b = a.clone()+ b[0] += 0.125+ b[1] += 0.375+ expected = torch.tensor(-10.0 * math.log10(2.0 / (0.125**2 + 0.375**2)), device=device, dtype=dtype)+ self.assert_close(kornia.losses.psnr_loss(a, b, 1.0), expected)+ self.assert_close(kornia.losses.PSNRLoss(1.0)(a, b), expected)+ assert kornia.losses.psnr_loss(a, a, 1.0).item() == -math.infdiff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.pyindex 0f827f97a..a30f922df 100644--- a/tests/losses/test_ssim.py+++ b/tests/losses/test_ssim.py@@ -19,6 +19,7 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -511,3 +512,107 @@ class TestSSIM3DLoss(BaseTester):@pytest.mark.skip("loss have no exception case")def test_exception(self):pass+++class TestConventionsSSIMLoss(BaseTester):+ """Pins for the loss forms of :func:`ssim_loss`, :class:`MS_SSIMLoss` and :func:`ssim3d_loss` (#5533)."""++ @staticmethod+ def _pair(shape, device, dtype):+ # y is a noisy copy of x+ g = torch.Generator().manual_seed(0)+ x = torch.rand(shape, generator=g)+ y = (x + 0.3 * torch.randn(shape, generator=g)).clamp(0, 1)+ return x.to(device, dtype), y.to(device, dtype)++ def test_convention_ssim_loss_is_clamped_half_dissimilarity(self, device, dtype):+ g = torch.Generator().manual_seed(0)+ x = torch.rand(1, 1, 9, 11, generator=g).to(device=device, dtype=dtype)+ y = torch.rand(1, 1, 9, 11, generator=g).to(device=device, dtype=dtype)+ ssim_map = kornia.metrics.ssim(x, y, 5)+ expected = ((1.0 - ssim_map) / 2).clamp(0, 1).mean()+ self.assert_close(kornia.losses.ssim_loss(x, y, 5), expected)++ def test_convention_ssim_loss_clamps_roundoff_into_the_unit_range(self, device, dtype):+ # The clamp is inert in exact arithmetic, where the SSIM map lies in [-1, 1]. Images with a large constant+ # offset make the moments cancel and push the map far outside [-1, 1] on both sides; the loss stays in [0, 1].+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("ssim computes half images in float32, and a half image cannot hold the offset fixture")+ offset = 1000.0 if dtype == torch.float32 else 1e8+ g = torch.Generator().manual_seed(0)+ x = (offset + 1e-2 * torch.rand(2, 2, 23, 31, generator=g, dtype=torch.float64)).to(device, dtype)+ y = (offset + 1e-2 * torch.rand(2, 2, 23, 31, generator=g, dtype=torch.float64)).to(device, dtype)+ unclamped = (1.0 - kornia.metrics.ssim(x, y, 5)) / 2+ assert (unclamped < 0).any()+ assert (unclamped > 1).any()+ loss = kornia.losses.ssim_loss(x, y, 5, reduction="none")+ self.assert_close(loss, unclamped.clamp(0, 1))+ assert loss.min() >= 0+ assert loss.max() <= 1++ def test_convention_ssim_loss_reduction_defaults_to_mean(self, device, dtype):+ # 'none' keeps the per-pixel loss (B, C, H, W), cropped under padding='valid'; the default 'mean' and 'sum'+ # reduce every element; any other reduction raises. SSIMLoss is the same function.+ x, y = self._pair((2, 3, 13, 17), device, dtype)+ none = kornia.losses.ssim_loss(x, y, 5, reduction="none")+ assert none.shape == (2, 3, 13, 17)+ assert kornia.losses.ssim_loss(x, y, 5, reduction="none", padding="valid").shape == (2, 3, 9, 13)+ self.assert_close(kornia.losses.ssim_loss(x, y, 5), none.mean())+ self.assert_close(kornia.losses.ssim_loss(x, y, 5, reduction="sum"), none.sum())+ self.assert_close(kornia.losses.SSIMLoss(5)(x, y), none.mean())+ with pytest.raises((NotImplementedError, ValueError, BaseError)):+ kornia.losses.ssim_loss(x, y, 5, reduction="batchmean")++ def test_convention_ms_ssim_loss_default_weights_are_alpha_0_025_and_compensation_200(self, device, dtype):+ # The default loss is 200 * (0.025 * L_MS-SSIM + 0.975 * L1_G): the defaults of psyrocloud MS-SSIM_L1_LOSS;+ # NVlabs PL4NN shares alpha = 0.025 without the factor 200. Zhao et al. set alpha = 0.84 in the paper.+ x, y = self._pair((2, 3, 16, 20), device, dtype)++ def loss(**kwargs):+ return kornia.losses.MS_SSIMLoss(reduction="none", **kwargs).to(device, dtype)(x, y)++ expected = 200 * (0.025 * loss(alpha=1.0, compensation=1.0) + 0.975 * loss(alpha=0.0, compensation=1.0))+ tol = _MS_SSIM_TOL.get(dtype, 1e-4)+ self.assert_close(loss(), expected, rtol=tol, atol=tol)+ # the default reduction is 'mean' over the (B, H, W) map+ self.assert_close(kornia.losses.MS_SSIMLoss().to(device, dtype)(x, y), loss().mean())++ def test_convention_ms_ssim_loss_last_sigma_is_the_coarsest_scale(self, device, dtype):+ # The last entry of sigmas sets the window, the luminance scale and the Gaussian of the L1 term, so the order+ # matters: with alpha=0 the loss depends on sigmas[-1] alone, the last entry and not the largest one.+ x, y = self._pair((2, 3, 16, 20), device, dtype)++ def l1_term(sigmas):+ criterion = kornia.losses.MS_SSIMLoss(sigmas=sigmas, alpha=0.0, compensation=1.0, reduction="none")+ return criterion.to(device, dtype)(x, y)++ self.assert_close(l1_term((0.5, 2.0)), l1_term((2.0,)))+ self.assert_close(l1_term((2.0, 0.5)), l1_term((0.5,)))+ assert (l1_term((2.0, 0.5)) - l1_term((0.5, 2.0))).abs().max() > 1e-2++ def test_convention_ms_ssim_loss_data_range_scales_the_constants_not_the_pixels(self, device, dtype):+ # data_range scales C1 and C2 and divides the L1 term; the pixel values are never rescaled.+ x, y = self._pair((2, 3, 16, 20), device, dtype)+ expected = kornia.losses.MS_SSIMLoss().to(device, dtype)(x, y)+ scaled = kornia.losses.MS_SSIMLoss(data_range=256.0).to(device, dtype)(256 * x, 256 * y)+ tol = _MS_SSIM_TOL.get(dtype, 1e-4)+ self.assert_close(scaled, expected, rtol=tol, atol=tol)+ assert kornia.losses.MS_SSIMLoss().to(device, dtype)(256 * x, 256 * y) > 10 * expected++ def test_convention_ssim3d_loss_is_clamped_half_dissimilarity_5533(self, device, dtype):+ """ssim3d_loss is the clamped (1 - SSIM) / 2 per voxel (#5533)."""+ # Sample 0 is a noisy copy, while sample 1 is anti-correlated and gives negative SSIM.+ x, y = self._pair((2, 1, 6, 7, 9), device, dtype)+ y[1] = 1.0 - x[1]+ ssim_map = kornia.metrics.ssim3d(x, y, 5)+ loss = kornia.losses.ssim3d_loss(x, y, 5, reduction="none")+ expected = ((1.0 - ssim_map) / 2).clamp(0, 1)+ self.assert_close(loss, expected)+ self.assert_close(kornia.losses.SSIM3DLoss(5)(x, y), expected.mean())++ def test_convention_ssim3d_loss_is_bounded_5533(self, device, dtype):+ """ssim3d_loss stays in [0, 1] for anti-correlated volumes (#5533)."""+ g = torch.Generator().manual_seed(0)+ x = torch.rand(1, 1, 6, 7, 9, generator=g).to(device, dtype)+ loss = kornia.losses.ssim3d_loss(x, 1.0 - x, 5)+ assert 0.0 <= loss <= 1.0diff --git a/tests/losses/test_total_variation.py b/tests/losses/test_total_variation.pyindex 8713b0ec9..b11ea00a3 100644--- a/tests/losses/test_total_variation.py+++ b/tests/losses/test_total_variation.py@@ -19,6 +19,7 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -220,3 +221,37 @@ class TestTotalVariation(BaseTester):dtype = torch.float64image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)self.gradcheck(kornia.losses.total_variation, (image,))+++class TestConventionsTotalVariation(BaseTester):+ @staticmethod+ def _edges(device, dtype):+ # H = 5, W = 8. Channel 0 holds one vertical edge (a step along W in each of the 5 rows), channel 1 one+ # horizontal edge (a step along H in each of the 8 columns), channel 2 is constant; sample 1 doubles sample 0.+ img = torch.zeros(2, 3, 5, 8)+ img[:, 0, :, 3:] = 1.0+ img[:, 1, 2:, :] = 1.0+ img[:, 2] = 0.5+ img[1] *= 2+ return img.to(device, dtype)++ def test_convention_total_variation_sums_over_the_last_two_axes(self, device, dtype):+ # Anisotropic L1 total variation, sum |d/dy| + sum |d/dx| over the last two axes only: (B, C, H, W) gives+ # (B, C), with the channels kept apart. The default reduction is 'sum', and TotalVariation always sums.+ img = self._edges(device, dtype)+ expected = torch.tensor([[5.0, 8.0, 0.0], [10.0, 16.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(kornia.losses.total_variation(img), expected)+ self.assert_close(kornia.losses.TotalVariation()(img), expected)+ self.assert_close(kornia.losses.total_variation(img[0, 1]), expected[0, 1])++ def test_convention_total_variation_mean_divides_each_term_by_its_own_count(self, device, dtype):+ # 'mean' is mean |d/dy| over the (H - 1) W vertical differences plus mean |d/dx| over the H (W - 1) horizontal+ # ones: a vertical edge gives 1 / (W - 1) = 1/7 and a horizontal edge 1 / (H - 1) = 1/4, where dividing the sum+ # by H W would give 1/8 and 1/5. Only 'mean' and 'sum' are accepted.+ img = self._edges(device, dtype)+ expected = torch.tensor([[1 / 7, 1 / 4, 0.0], [2 / 7, 2 / 4, 0.0]], device=device, dtype=dtype)+ self.assert_close(kornia.losses.total_variation(img, reduction="mean"), expected)+ # Relabelling check: transposing the image transposes both counts with it, so the values stay.+ self.assert_close(kornia.losses.total_variation(img.transpose(-2, -1), reduction="mean"), expected)+ with pytest.raises((ValueError, BaseError)):+ kornia.losses.total_variation(img, reduction="none")diff --git a/tests/metrics/test_psnr_metric.py b/tests/metrics/test_psnr_metric.pyindex e35b5be51..ad7a4c77e 100644--- a/tests/metrics/test_psnr_metric.py+++ b/tests/metrics/test_psnr_metric.py@@ -15,10 +15,13 @@# limitations under the License.#+import math+import pytestimport torchimport kornia+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -102,3 +105,62 @@ class TestPsnr(BaseTester):b = torch.ones(8, device=device, dtype=dtype)with pytest.raises(TypeError, match="Expected tensors of equal shapes"):kornia.metrics.psnr(a, b, max_val=1.0)+++class TestConventionsPsnr(BaseTester):+ """Pins for the batch pooling, ``max_val``, identical images and integer images of :func:`psnr`."""++ def test_convention_psnr_pools_mse_over_the_batch(self, device, dtype):+ a = torch.zeros(2, 1, 4, 6, device=device, dtype=dtype)+ b = a.clone()+ b[0] += 0.125+ b[1] += 0.375+ # one MSE over every element of the batch: (0.125**2 + 0.375**2) / 2 -> 10 log10(1 / mse) = 11.0721,+ # not the mean of the per-image PSNRs (18.0618 and 8.5194 -> 13.2906)+ expected = torch.tensor(10.0 * math.log10(2.0 / (0.125**2 + 0.375**2)), device=device, dtype=dtype)+ self.assert_close(kornia.metrics.psnr(a, b, 1.0), expected)++ def test_convention_psnr_max_val_is_the_data_range(self, device, dtype):+ # max_val is MAX_I in 10 log10(MAX_I**2 / MSE), the data range rather than the largest value of the images:+ # images and max_val scaled together keep the value, and max_val=2 gives 10 log10(4 / mse) = 17.0927 on images+ # whose largest value is 0.375. An int max_val is accepted.+ a = torch.zeros(2, 1, 4, 6, device=device, dtype=dtype)+ b = a.clone()+ b[0] += 0.125+ b[1] += 0.375+ expected = torch.tensor(10.0 * math.log10(4.0 * 2.0 / (0.125**2 + 0.375**2)), device=device, dtype=dtype)+ self.assert_close(kornia.metrics.psnr(a, b, 2.0), expected)+ self.assert_close(kornia.metrics.psnr(a, b, 2), expected)+ self.assert_close(kornia.metrics.psnr(8 * a, 8 * b, 16.0), expected)++ def test_convention_psnr_identical_images_give_inf(self, device, dtype):+ # identical images give MSE 0 and +inf; a batch in which only one pair is identical stays finite, because the+ # MSE is pooled: 10 log10(2 / 0.375**2) = 11.5297+ a = torch.zeros(2, 1, 4, 6, device=device, dtype=dtype)+ a[:, :, 1:, 2:] = 0.5+ assert kornia.metrics.psnr(a, a, 1.0).item() == math.inf+ b = a.clone()+ b[1] += 0.375+ expected = torch.tensor(10.0 * math.log10(2.0 / 0.375**2), device=device, dtype=dtype)+ self.assert_close(kornia.metrics.psnr(a, b, 1.0), expected)++ def test_convention_psnr_needs_equal_shapes(self, device, dtype):+ # image and target must have the same shape, with no broadcasting, and the metric is symmetric in them+ a = torch.zeros(2, 1, 4, 6, device=device, dtype=dtype)+ b = torch.full((1, 1, 4, 6), 0.25, device=device, dtype=dtype)+ with pytest.raises((TypeError, ValueError, BaseError)):+ kornia.metrics.psnr(a, b, 1.0)+ b = b.expand(2, 1, 4, 6).clone()+ b[1, :, :, :3] = 0.75+ self.assert_close(kornia.metrics.psnr(b, a, 1.0), kornia.metrics.psnr(a, b, 1.0))++ def test_convention_psnr_computes_integer_images_in_float32_5536(self, device, dtype):+ """psnr computes integer images in float32, matching its float32 inputs (#5536)."""+ # These uint8 differences wrap when left unconverted, so this pair detects either an error or a wrong result.+ a = torch.tensor([[0, 64, 128], [192, 255, 32]], dtype=torch.uint8).view(1, 1, 2, 3).to(device)+ b = torch.tensor([[16, 64, 100], [200, 250, 0]], dtype=torch.uint8).view(1, 1, 2, 3).to(device)+ expected = kornia.metrics.psnr(a.float(), b.float(), 255.0)+ actual = kornia.metrics.psnr(a, b, 255.0)+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, rtol=0.0, atol=0.0)+ assert torch.isfinite(kornia.metrics.psnr(a.to(dtype), b.to(dtype), 255.0))diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.pyindex ae85f97a2..74824c1e3 100644--- a/tests/metrics/test_ssim3d.py+++ b/tests/metrics/test_ssim3d.py@@ -17,8 +17,10 @@import pytestimport torch+import torch.nn.functional as Fimport kornia+from kornia.core.exceptions import BaseErrorfrom testing.base import BaseTester@@ -162,8 +164,6 @@ class TestSSIM3d(BaseTester):@pytest.mark.parametrize("padding", ["full", "bogus"])def test_exception_invalid_padding(self, device, dtype, padding):# Any other value raises instead of silently returning the 'same' map (#5537).- from kornia.core.exceptions import BaseError-img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=dtype)with pytest.raises(BaseError, match="Invalid padding mode"):kornia.metrics.ssim3d(img, img, 3, padding=padding)@@ -301,3 +301,79 @@ class TestSSIM3d(BaseTester):op = kornia.metrics.ssim3dself.gradcheck(op, (img, img, 3), nondet_tol=1e-8)+++class TestConventionsSSIM3D(BaseTester):+ """Pins for the map shape of :func:`ssim3d`, its reflected border, its window dtype and ``padding`` validation."""++ @staticmethod+ def _pair(device, dtype):+ # a two-sample, two-channel batch with D != H != W; y is a noisy copy of x+ g = torch.Generator().manual_seed(0)+ x = torch.rand(2, 2, 6, 7, 9, generator=g)+ y = (x + 0.3 * torch.randn(2, 2, 6, 7, 9, generator=g)).clamp(0, 1)+ return x.to(device, dtype), y.to(device, dtype)++ def test_convention_ssim3d_map_shape_and_valid_crop(self, device, dtype):+ # ssim3d scores every voxel of (B, C, D, H, W); 'valid' crops (window_size - 1) / 2 voxels from both ends of+ # each of D, H and W, and equals the 'same' map with that border cut off.+ x, y = self._pair(device, dtype)+ same = kornia.metrics.ssim3d(x, y, 5)+ valid = kornia.metrics.ssim3d(x, y, 5, padding="valid")+ assert same.shape == (2, 2, 6, 7, 9)+ assert valid.shape == (2, 2, 2, 3, 5)+ self.assert_close(valid, same[..., 2:-2, 2:-2, 2:-2])+ # Relabelling check: swapping D and W in both volumes swaps them in the map (the window is isotropic).+ swapped = kornia.metrics.ssim3d(x.transpose(-3, -1), y.transpose(-3, -1), 5)+ self.assert_close(swapped, same.transpose(-3, -1))++ def test_convention_ssim3d_same_border_is_reflect_5534(self, device, dtype):+ """The 'same' border of ssim3d reflects, as ssim does (#5534)."""+ # The 'same' map equals the 'valid' map of reflect-padded volumes and differs from replicate padding at the+ # border.+ x, y = self._pair(device, dtype)+ work = torch.promote_types(dtype, torch.float32) # ssim3d computes half-precision volumes in float32++ def padded(mode):+ xp = F.pad(x.to(work), (2, 2, 2, 2, 2, 2), mode=mode)+ yp = F.pad(y.to(work), (2, 2, 2, 2, 2, 2), mode=mode)+ return kornia.metrics.ssim3d(xp, yp, 5, padding="valid").to(dtype)++ same = kornia.metrics.ssim3d(x, y, 5)+ self.assert_close(same, padded("reflect"))+ assert (same - padded("replicate")).abs().max() > 0.1++ def test_convention_ssim3d_window_uses_input_dtype_5534(self, device, dtype):+ """ssim3d builds its Gaussian window in the input dtype (#5534)."""+ # A float64 ssim3d equals a float64 SSIM computed with a float64 window, rather than a float32-rounded one.+ # The comparison runs on the valid voxels.+ if dtype != torch.float64:+ pytest.skip("the input window dtype differs from float32 only for float64 inputs")+ g = torch.Generator().manual_seed(0)+ x = torch.rand(1, 1, 6, 7, 9, generator=g, dtype=torch.float64).to(device)+ y = torch.rand(1, 1, 6, 7, 9, generator=g, dtype=torch.float64).to(device)++ def reference(window_dtype):+ window = kornia.filters.get_gaussian_kernel3d((5, 5, 5), (1.5, 1.5, 1.5), dtype=window_dtype)+ window = window.to(device, torch.float64)[None]++ def blur(t):+ return F.conv3d(t, window)++ mu_x, mu_y = blur(x), blur(y)+ var_x, var_y = blur(x * x) - mu_x**2, blur(y * y) - mu_y**2+ cov = blur(x * y) - mu_x * mu_y+ c1, c2 = 0.01**2, 0.03**2+ return (2 * mu_x * mu_y + c1) * (2 * cov + c2) / ((mu_x**2 + mu_y**2 + c1) * (var_x + var_y + c2) + 1e-12)++ actual = kornia.metrics.ssim3d(x, y, 5, padding="valid")+ assert (actual - reference(torch.float64)).abs().max() < 1e-13+ assert (actual - reference(torch.float32)).abs().max() > 1e-9++ def test_convention_ssim3d_padding_is_case_insensitive_and_validated_5537(self, device, dtype):+ """'VALID' selects the valid map, while an unknown padding mode raises (#5537)."""+ x, y = self._pair(device, dtype)+ valid = kornia.metrics.ssim3d(x, y, 5, padding="valid")+ self.assert_close(kornia.metrics.ssim3d(x, y, 5, padding="VALID"), valid, rtol=0.0, atol=0.0)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ kornia.metrics.ssim3d(x, y, 5, padding="bogus")diff --git a/tests/metrics/test_ssim_metric.py b/tests/metrics/test_ssim_metric.pyindex e94a44777..7e642c52e 100644--- a/tests/metrics/test_ssim_metric.py+++ b/tests/metrics/test_ssim_metric.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport pytestimport torch+import torch.nn.functional as Ffrom kornia.core.exceptions import BaseErrorfrom kornia.metrics.ssim import SSIM, ssim@@ -212,3 +213,118 @@ class TestSsim(BaseTester):out_module = module(img1, img2)out_fn = ssim(img1, img2, window_size=5)assert out_module.shape == out_fn.shape+++class TestConventionsSSIM(BaseTester):+ """Pins for the map shape, the border, the window, ``max_val`` and ``padding`` validation of :func:`ssim`."""++ @staticmethod+ def _pair(device, dtype):+ # a two-sample, three-channel batch with H != W; y is a noisy copy of x+ g = torch.Generator().manual_seed(0)+ x = torch.rand(2, 3, 13, 17, generator=g)+ y = (x + 0.3 * torch.randn(2, 3, 13, 17, generator=g)).clamp(0, 1)+ return x.to(device, dtype), y.to(device, dtype)++ def test_convention_ssim_map_shape_and_valid_crop(self, device, dtype):+ # 'same' returns the per-pixel map (B, C, H, W). 'valid' crops (window_size - 1) / 2 pixels per side, giving+ # (B, C, H - window_size + 1, W - window_size + 1), and equals the 'same' map with that border cut off.+ x, y = self._pair(device, dtype)+ same = ssim(x, y, 5)+ valid = ssim(x, y, 5, padding="valid")+ assert same.shape == (2, 3, 13, 17)+ assert valid.shape == (2, 3, 9, 13)+ self.assert_close(valid, same[..., 2:-2, 2:-2])+ # Relabelling check: transposing both images transposes the map.+ self.assert_close(ssim(x.transpose(-2, -1), y.transpose(-2, -1), 5), same.transpose(-2, -1))+ # window_size is the odd tap count of the Gaussian window+ with pytest.raises((ValueError, BaseError)):+ ssim(x, y, 4)++ def test_convention_ssim_same_border_is_reflect(self, device, dtype):+ # 'same' pads with torch's 'reflect', which does not repeat the edge pixel: the 'same' map equals the 'valid'+ # map of the reflect-padded images. Padding by 'replicate' instead changes the border.+ x, y = self._pair(device, dtype)+ work = torch.promote_types(dtype, torch.float32) # ssim computes half-precision images in float32++ def padded(mode):+ xp = F.pad(x.to(work), (2, 2, 2, 2), mode=mode)+ yp = F.pad(y.to(work), (2, 2, 2, 2), mode=mode)+ return ssim(xp, yp, 5, padding="valid").to(dtype)++ same = ssim(x, y, 5)+ self.assert_close(same, padded("reflect"))+ assert (same - padded("replicate")).abs().max() > 0.1++ def test_convention_ssim_matches_scikit_image_gaussian_ssim(self, device, dtype):+ # The window is a sampled Gaussian with sigma = 1.5 whatever window_size is; window_size=11 with 'valid' and+ # eps=0 matches scikit-image's Gaussian SSIM (Wang et al. 2004), averaged over the channels.+ # Snippet used to generate expected (scikit-image 0.26.0, numpy 2.0.0):+ # x = (np.arange(2 * 13 * 17).reshape(2, 13, 17) * 7 % 11) / 16+ # structural_similarity(x, x**2, gaussian_weights=True, sigma=1.5, use_sample_covariance=False,+ # data_range=1.0, channel_axis=0)+ x = (torch.arange(2 * 13 * 17, dtype=torch.float32).reshape(1, 2, 13, 17) * 7 % 11) / 16+ x = x.to(device, dtype)+ actual = ssim(x, x**2, 11, max_val=1.0, eps=0.0, padding="valid").mean()+ self.assert_close(actual, torch.tensor(0.649510247445418, device=device, dtype=dtype))+ # The same sigma at another size: window_size=7 equals SSIM with a sampled 7-tap Gaussian of sigma 1.5 and+ # reflect padding, written out with the default constants C1 = 0.01**2, C2 = 0.03**2 and eps.+ x, y = self._pair(device, dtype)+ work = torch.promote_types(dtype, torch.float32) # ssim computes half-precision images in float32+ k = torch.exp(-((torch.arange(7, dtype=torch.float64) - 3) ** 2) / (2 * 1.5**2))+ k = (k / k.sum()).to(device, work)+ kernel = (k[:, None] * k[None, :]).expand(3, 1, 7, 7)++ def blur(t):+ return F.conv2d(F.pad(t, (3, 3, 3, 3), mode="reflect"), kernel, groups=3)++ xw, yw = x.to(work), y.to(work)+ mx, my = blur(xw), blur(yw)+ sx, sy, sxy = blur(xw * xw) - mx**2, blur(yw * yw) - my**2, blur(xw * yw) - mx * my+ expected = (2 * mx * my + 1e-4) * (2 * sxy + 9e-4) / ((mx**2 + my**2 + 1e-4) * (sx + sy + 9e-4) + 1e-12)+ self.assert_close(ssim(x, y, 7), expected.to(dtype))++ @pytest.mark.parametrize(+ "max_val,expected",+ [(1.0, 0.9999888890123443), (0.1, 0.9), (0.01, 0.0008991907283444898)],+ )+ def test_convention_ssim_epsilon_biases_identical_black_images(self, device, dtype, max_val, expected):+ # Identical black images have SSIM 1 in the reference implementations. Kornia's denominator epsilon changes+ # the score to C1*C2/(C1*C2 + eps), even at max_val=1; at small ranges the difference is substantial.+ # The expected values use C1=(0.01*max_val)**2, C2=(0.03*max_val)**2, eps=1e-12 in float64 arithmetic.+ x = torch.zeros(1, 1, 13, 17, device=device, dtype=dtype)+ score = ssim(x, x, 11, max_val=max_val, padding="valid").mean()+ self.assert_close(score, x.new_tensor(expected))+ reference = ssim(x, x, 11, max_val=max_val, eps=0.0, padding="valid").mean()+ self.assert_close(reference, x.new_tensor(1.0), rtol=0.0, atol=0.0)+ if max_val < 1.0:+ assert (reference - score) > 0.05++ def test_convention_ssim_max_val_is_the_data_range(self, device, dtype):+ # max_val is the data range L in C1 = (0.01 L)**2 and C2 = (0.03 L)**2: images and max_val scaled together give+ # the same map, and the default max_val=1.0 on the scaled images gives another one (the range is not inferred).+ x, y = self._pair(device, dtype)+ expected = ssim(x, y, 5)+ self.assert_close(ssim(256 * x, 256 * y, 5, max_val=256.0), expected)+ assert (ssim(256 * x, 256 * y, 5) - expected).abs().max() > 0.01++ def test_convention_ssim_is_per_sample_and_per_channel(self, device, dtype):+ # Every (sample, channel) plane is scored on its own, and the map is symmetric in (img1, img2).+ x, y = self._pair(device, dtype)+ base = ssim(x, y, 5)+ y_moved = y.clone()+ y_moved[1, 1] = 1.0 - y_moved[1, 1]+ moved = ssim(x, y_moved, 5)+ self.assert_close(moved[0], base[0])+ self.assert_close(moved[1, 0], base[1, 0])+ self.assert_close(moved[1, 2], base[1, 2])+ assert (moved[1, 1] - base[1, 1]).abs().max() > 0.1+ self.assert_close(ssim(y, x, 5), base)++ def test_convention_ssim_padding_is_case_insensitive_and_validated_5537(self, device, dtype):+ """'VALID' selects the valid map, while an unknown padding mode raises (#5537)."""+ x, y = self._pair(device, dtype)+ valid = ssim(x, y, 5, padding="valid")+ self.assert_close(ssim(x, y, 5, padding="VALID"), valid, rtol=0.0, atol=0.0)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ ssim(x, y, 5, padding="bogus")