Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(losses): focal_loss computes the target log-probability without full-size CPU buffers (#6081)

Dmytro Mishkinfdd67e24b7ab
diff --git a/changelog.d/6081.fixed.md b/changelog.d/6081.fixed.md
new file mode 100644
index 000000000..1fc99cd11
--- /dev/null
+++ b/changelog.d/6081.fixed.md
@@ -0,0 +1,9 @@
+`focal_loss` and `FocalLoss` run faster on the CPU for `'mean'` and `'sum'` without class weights, on float32 and
+float64 logits with at least 2**19 values: the target-class log-probability comes from a custom autograd function that
+works through the batch in chunks and saves only the logits and two values per pixel, instead of a full-size
+`log_softmax` whose output and gradients were fresh memory faulted in on every call. On 21-class 256 x 256 logits,
+forward plus backward, measured on an i7-14700K under WSL2 (where page faults cost more than on native Linux), the loss
+is 1.9x faster at batch 8 and 1.8x at batch 32 in eager mode, 1.4x at both with the faults removed from both paths by
+`GLIBC_TUNABLES`, and 1.16x at batch 8 under `torch.compile`. Values and gradients agree with `log_softmax` to rounding,
+with the same NaN and infinity positions; double backward is supported, and exported, traced, autocast, functorch and
+forward-mode AD calls keep `log_softmax`.
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 729605b9f..916a0183e 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -17,18 +17,153 @@
from __future__ import annotations
-from typing import Optional
+from typing import Any, Optional
import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.utils import is_autocast_enabled, is_compiling, is_exporting
from kornia.losses._utils import mask_ignore_pixels
from kornia.losses.one_hot import _check_class_labels, one_hot
# based on:
# https://github.com/zhezh/focalloss/blob/master/focalloss.py
+# Logits per batch chunk of the CPU target log-probability, at least one sample: a chunk's temporary is reused from
+# the heap instead of being a fresh, page-faulted buffer, and stays in the cache between its passes.
+_CPU_CHUNK_BYTES = 2 * 1024 * 1024
+# Measured forward + backward, 4 threads: the custom function's fixed cost (about 25 us) loses below about 2**18
+# logits (0.8x for a handful) and breaks even up to 21 x 128 x 128; from 2**19 the full-size buffers it avoids
+# dominate.
+_CPU_MIN_NUMEL = 1 << 19
+
+
+def _focal_loss_cpu_eligible(pred: torch.Tensor) -> bool:
+ """Select large native-precision CPU logits, whose full-size log-softmax buffers are fresh memory on every call."""
+ # Keep log_softmax where it is what the caller captures or transforms: the exporters and the legacy tracer record
+ # it, functorch transforms (vmap, grad, jvp) need no custom function, and autocast chooses its precision.
+ # Forward-mode AD keeps it too: Dynamo cannot capture an autograd function that defines a jvp, so a jvp would
+ # break every compiled training graph, and a jvp built on the saved statistics is not differentiable again.
+ return (
+ pred.device.type == "cpu"
+ and pred.dtype in (torch.float32, torch.float64)
+ # Before the size check: torch.export would turn it into a guard of the exported program, which then fails at
+ # run time for logits on the other side of the threshold although its dynamic shapes allow them.
+ and not is_exporting()
+ # Before the size check, which the legacy tracer would record as a constant with a TracerWarning.
+ and not torch.jit.is_tracing()
+ and pred.numel() >= _CPU_MIN_NUMEL
+ and not torch._C._are_functorch_transforms_active()
+ and not is_autocast_enabled()
+ and torch.autograd.forward_ad.unpack_dual(pred).tangent is None
+ )
+
+
+def _batch_chunks(pred: torch.Tensor, *tensors: Optional[torch.Tensor]) -> list[tuple[Any, ...]]:
+ """Split ``pred`` and ``tensors`` (``None`` stays ``None``) into the same batch chunks of about 2 MB of logits."""
+ sample_bytes = pred.numel() // max(1, pred.shape[0]) * pred.element_size()
+ step = max(1, _CPU_CHUNK_BYTES // max(1, sample_bytes))
+ if step >= pred.shape[0]:
+ return [(pred, *tensors)]
+ splits = [t.split(step) if t is not None else None for t in (pred, *tensors)]
+ return [tuple(s[i] if s is not None else None for s in splits) for i in range(len(splits[0]))]
+
+
+def _target_log_softmax_values(
+ pred: torch.Tensor, target: torch.Tensor, valid: Optional[torch.Tensor], inplace: bool
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """``log_softmax(where(valid, pred, 0), 1).gather(1, target)``, and the maximum and log-sum of each position.
+
+ The log-probability is ``(x - max) - log(sum(exp(x - max)))``, in that order, as in ``log_softmax``'s CPU kernel.
+ """
+ x = pred if valid is None else torch.where(valid, pred, 0.0)
+ # A NaN or +inf logit, or a position whose logits are all -inf, makes the log-sum NaN, as in log_softmax.
+ x_max = x.amax(1, keepdim=True)
+ x_target = x.gather(1, target)
+ if inplace:
+ # x is a temporary of this function unless it is pred itself.
+ log_sum = (x.sub_(x_max) if valid is not None else x - x_max).exp_().sum(1, keepdim=True).log_()
+ else:
+ log_sum = (x - x_max).exp().sum(1, keepdim=True).log()
+ return (x_target - x_max) - log_sum, x_max, log_sum
+
+
+class _TargetLogSoftmax(torch.autograd.Function):
+ r"""Target-class log-probability ``log_softmax(where(valid, pred, 0), 1).gather(1, target)`` of CPU logits.
+
+ ``log_softmax`` saves a full-size output for its backward, and the ``gather`` and ``masked_fill`` backwards each
+ allocate another full-size gradient: on a large CPU batch, fresh memory that is faulted in on every call. This
+ saves ``pred`` itself and the maximum and log-sum of each position, and the backward writes
+ :math:`(\text{onehot}(t) - \text{softmax}) \cdot g` straight into the one gradient buffer, a batch chunk at a time.
+ The logits are masked as ``log_softmax``'s input was, so NaN and infinity positions are the same, and the gradient
+ at a position that is not ``valid`` is exactly 0, as ``masked_fill``'s backward made it. ``torch.compile`` and
+ functorch get the same arithmetic out of place and unchunked; a double backward differentiates a softmax
+ recomputed from ``pred``. Forward-mode AD never reaches it (see :func:`_focal_loss_cpu_eligible`).
+ """
+
+ @staticmethod
+ def forward(ctx: Any, pred: torch.Tensor, target: torch.Tensor, valid: Optional[torch.Tensor]) -> torch.Tensor:
+ if is_compiling() or torch._C._are_functorch_transforms_active():
+ log_prob, x_max, log_sum = _target_log_softmax_values(pred, target, valid, inplace=False)
+ else:
+ parts = [
+ _target_log_softmax_values(p, t, v, inplace=True) for p, t, v in _batch_chunks(pred, target, valid)
+ ]
+ if len(parts) == 1:
+ log_prob, x_max, log_sum = parts[0]
+ else:
+ log_prob, x_max, log_sum = (torch.cat([part[i] for part in parts]) for i in range(3))
+ ctx.save_for_backward(pred, target, valid, x_max, log_sum)
+ return log_prob
+
+ @staticmethod
+ def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
+ pred, target, valid, x_max, log_sum = ctx.saved_tensors
+ if torch.is_grad_enabled():
+ # create_graph: the saved maximum and log-sum have no history, so differentiate a softmax recomputed from
+ # pred.
+ x = pred if valid is None else torch.where(valid, pred, 0.0)
+ grad = (x.softmax(1) * -grad_output).scatter_add(1, target, grad_output)
+ return (grad if valid is None else torch.where(valid, grad, 0.0)), None, None
+ # Out of place under compile and functorch, and for a batched (autograd.grad(is_grads_batched=True), legacy
+ # vmap) or dual (forward-over-reverse) incoming gradient, which cannot be written into one plain buffer.
+ if (
+ is_compiling()
+ or torch._C._are_functorch_transforms_active()
+ or torch._C._functorch.is_legacy_batchedtensor(grad_output)
+ or torch.autograd.forward_ad.unpack_dual(grad_output).tangent is not None
+ ):
+ grad = (((pred - x_max) - log_sum).exp() * -grad_output).scatter_add(1, target, grad_output)
+ return (grad if valid is None else torch.where(valid, grad, 0.0)), None, None
+ # Contiguous for any layout of pred, as the gather backward of the log_softmax path makes its gradient.
+ grad = torch.empty_like(pred, memory_format=torch.contiguous_format)
+ neg_grad_output = -grad_output
+ for p, g, t, v, m, ls, go, neg_go in _batch_chunks(
+ pred, grad, target, valid, x_max, log_sum, grad_output, neg_grad_output
+ ):
+ torch.sub(p, m, out=g)
+ g.sub_(ls).exp_().mul_(neg_go).scatter_add_(1, t, go)
+ if v is not None:
+ g.masked_fill_(~v, 0.0)
+ return grad, None, None
+
+
+def _masked_log_softmax(
+ pred: torch.Tensor, target: torch.Tensor, target_mask: Optional[torch.Tensor], reduced: bool
+) -> torch.Tensor:
+ """Log-softmax over dim 1 of ``pred``, positions outside ``target_mask`` set to 0; at ``target`` if reduced."""
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
+ if reduced and _focal_loss_cpu_eligible(pred):
+ return _TargetLogSoftmax.apply(pred, target.unsqueeze(1), target_mask)
+ if target_mask is not None:
+ # Exclude ignored logits before log-softmax: an overflowing log probability times zero is NaN.
+ pred = pred.masked_fill(~target_mask, 0.0)
+ log_pred_soft = pred.log_softmax(1)
+ if reduced:
+ log_pred_soft = log_pred_soft.gather(1, target.unsqueeze(1))
+ return log_pred_soft
+
def focal_loss(
pred: torch.Tensor,
@@ -70,6 +205,12 @@ def focal_loss(
:ref:`Losses and metrics <losses-metrics-conventions>` ports
:func:`~torch.nn.functional.cross_entropy` to this loss.
- ``alpha`` outside ``[0, 1]`` and a negative ``gamma`` are not validated.
+ - On the CPU, ``'mean'`` and ``'sum'`` without ``weight``, with a finite ``gamma >= 0`` and ``alpha`` ``None``
+ or a number in ``[0, 1]``, of float32 or float64 logits with at least :math:`2^{19}` values compute the
+ target-class log-probability with a custom autograd function, a batch chunk at a time, instead of a
+ full-size ``log_softmax``, unless ``torch.export`` or ``torch.jit.trace`` captures the call, a functorch
+ transform or forward-mode AD runs, or autocast is on. It agrees with ``log_softmax`` to rounding, with the
+ same NaN and infinity positions and a zero gradient at ignored pixels, and supports double backward.
Args:
pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
@@ -133,12 +274,8 @@ def focal_loss(
target_mask = target_mask.unsqueeze(1)
if target_one_hot is not None:
target_one_hot = target_one_hot * target_mask
- # Exclude ignored logits before log-softmax: an overflowing log probability times zero is NaN.
- pred = pred.masked_fill(~target_mask, 0.0)
- log_pred_soft = pred.log_softmax(1)
- if reduced:
- log_pred_soft = log_pred_soft.gather(1, target.unsqueeze(1))
+ log_pred_soft = _masked_log_softmax(pred, target, target_mask, reduced)
# compute the actual focal loss
# For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0, so a probability that rounds to 1 gives a
diff --git a/tests/losses/test_focal_loss_cpu.py b/tests/losses/test_focal_loss_cpu.py
new file mode 100644
index 000000000..e0f695749
--- /dev/null
+++ b/tests/losses/test_focal_loss_cpu.py
@@ -0,0 +1,412 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import importlib
+import warnings
+from typing import Optional
+
+import pytest
+import torch
+
+from kornia.losses import FocalLoss, focal_loss
+
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+
+focal_module = importlib.import_module("kornia.losses.focal")
+
+# 2 x 21 x 128 x 128 logits reach the CPU path's size threshold; the 21 classes are those of the flagship benchmark.
+LARGE = (2, 21, 128, 128)
+
+
+def _require_native_cpu(device: torch.device, dtype: torch.dtype) -> None:
+ if device.type != "cpu" or dtype not in (torch.float32, torch.float64):
+ pytest.skip("the CPU target log-probability path supports native CPU float32 and float64 only")
+
+
+def _inputs(shape, device, dtype, ignore_index: Optional[int] = -100, seed: int = 0):
+ generator = torch.Generator().manual_seed(seed)
+ logits = (3 * torch.randn(shape, generator=generator)).to(device=device, dtype=dtype)
+ labels = torch.randint(shape[1], (shape[0], *shape[2:]), generator=generator)
+ if ignore_index is not None:
+ labels[torch.rand(labels.shape, generator=generator) < 0.2] = ignore_index
+ return logits, labels.to(device)
+
+
+def _value_and_grad(logits, labels, *args, **kwargs):
+ logits = logits.detach().clone().requires_grad_()
+ loss = focal_loss(logits, labels, *args, **kwargs)
+ (grad,) = torch.autograd.grad(loss, logits)
+ return loss, grad
+
+
+def _reference(monkeypatch, logits, labels, *args, **kwargs):
+ """Value and gradient of the log_softmax path: masked log_softmax, then gather."""
+ with monkeypatch.context() as patch:
+ patch.setattr(focal_module, "_focal_loss_cpu_eligible", lambda pred: False)
+ return _value_and_grad(logits, labels, *args, **kwargs)
+
+
+def _count_calls(monkeypatch) -> list:
+ calls = []
+ apply = focal_module._TargetLogSoftmax.apply
+
+ def counting(*args):
+ calls.append(args[0].shape)
+ return apply(*args)
+
+ monkeypatch.setattr(focal_module._TargetLogSoftmax, "apply", counting)
+ return calls
+
+
+class TestFocalLossCpu(BaseTester):
+ def assert_close_scaled(self, actual: torch.Tensor, expected: torch.Tensor) -> None:
+ """``assert_close`` relative to the largest finite entry of ``expected``.
+
+ A mean over a large batch makes gradients of about 1 / (B H W), far below the absolute tolerance, so both
+ sides are divided by that entry first; the dtype tolerances then bound the error relative to it.
+ """
+ finite = expected[expected.isfinite()]
+ scale = finite.abs().max() if finite.numel() else expected.new_ones(())
+ scale = torch.where(scale > 0, scale, torch.ones_like(scale))
+ self.assert_close(actual / scale, expected / scale)
+
+ def assert_close_with_nan(self, actual: torch.Tensor, expected: torch.Tensor) -> None:
+ assert torch.equal(actual.isnan(), expected.isnan())
+ self.assert_close_scaled(actual.masked_fill(actual.isnan(), 0), expected.masked_fill(expected.isnan(), 0))
+
+ @pytest.mark.parametrize("reduction", ["mean", "sum"])
+ def test_large_reduced_input_takes_the_cpu_path(self, monkeypatch, reduction, device, dtype):
+ _require_native_cpu(device, dtype)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs(LARGE, device, dtype)
+ _value_and_grad(logits, labels, 0.25, 2.0, reduction)
+ assert calls == [LARGE]
+
+ @pytest.mark.parametrize("mode", ["no_grad", "inference_mode"])
+ def test_without_recorded_gradients_takes_the_cpu_path(self, monkeypatch, mode, device, dtype):
+ _require_native_cpu(device, dtype)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs(LARGE, device, dtype)
+ logits.requires_grad_()
+ with torch.no_grad() if mode == "no_grad" else torch.inference_mode():
+ focal_loss(logits, labels, 0.25, 2.0, "mean")
+ assert len(calls) == 1
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"reduction": "none"},
+ {"reduction": "mean", "weight": "ones"},
+ {"reduction": "mean", "alpha": "tensor"},
+ {"reduction": "mean", "gamma": -1.0},
+ {"reduction": "mean", "shape": (2, 21, 64, 64)},
+ ],
+ ids=["none", "weight", "tensor-alpha", "negative-gamma", "small"],
+ )
+ def test_other_inputs_keep_log_softmax(self, monkeypatch, kwargs, device, dtype):
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs(kwargs.get("shape", LARGE), device, dtype)
+ alpha = torch.tensor(0.25, device=device) if kwargs.get("alpha") == "tensor" else 0.25
+ weight = torch.ones(logits.shape[1], device=device, dtype=dtype) if kwargs.get("weight") else None
+ focal_loss(logits, labels, alpha, kwargs.get("gamma", 2.0), kwargs["reduction"], weight)
+ assert calls == []
+
+ def test_captures_and_transforms_keep_log_softmax(self, monkeypatch, device, dtype):
+ _require_native_cpu(device, dtype)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs(LARGE, device, dtype)
+ torch.jit.trace(lambda x: focal_loss(x, labels, 0.25, 2.0, "mean"), (logits,), check_trace=False)
+ torch.func.grad(lambda x: focal_loss(x, labels, 0.25, 2.0, "mean"))(logits)
+ torch.vmap(lambda x: focal_loss(x[None], labels[:1], 0.25, 2.0, "mean"))(logits)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ focal_loss(logits, labels, 0.25, 2.0, "mean")
+ assert calls == []
+
+ @pytest.mark.parametrize("reduction", ["mean", "sum"])
+ @pytest.mark.parametrize("gamma", [0.0, 0.5, 2.0])
+ @pytest.mark.parametrize("alpha", [None, 0.25])
+ @pytest.mark.parametrize("ignore_index", [None, -100, 255])
+ def test_matches_log_softmax(self, monkeypatch, reduction, gamma, alpha, ignore_index, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype, ignore_index)
+ kwargs = {"ignore_index": ignore_index}
+ expected, expected_grad = _reference(monkeypatch, logits, labels, alpha, gamma, reduction, **kwargs)
+ actual, grad = _value_and_grad(logits, labels, alpha, gamma, reduction, **kwargs)
+ self.assert_close(actual, expected)
+ self.assert_close_scaled(grad, expected_grad)
+
+ @pytest.mark.parametrize("shape", [(5, 4), (5, 4, 3, 5), (5, 3, 2, 3, 4), (0, 4, 3), (5, 4, 0)])
+ def test_shapes_and_uneven_chunks_match_log_softmax(self, monkeypatch, shape, device, dtype):
+ _require_native_cpu(device, dtype)
+ # Two samples per chunk: five samples leave a last chunk of one.
+ sample_bytes = max(1, torch.Size(shape[1:]).numel()) * torch.empty((), dtype=dtype).element_size()
+ monkeypatch.setattr(focal_module, "_CPU_CHUNK_BYTES", 2 * sample_bytes)
+ monkeypatch.setattr(focal_module, "_CPU_MIN_NUMEL", 0)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs(shape, device, dtype)
+ for reduction in ("mean", "sum"):
+ expected, expected_grad = _reference(monkeypatch, logits, labels, 0.25, 2.0, reduction)
+ actual, grad = _value_and_grad(logits, labels, 0.25, 2.0, reduction)
+ self.assert_close_with_nan(actual, expected)
+ self.assert_close_scaled(grad, expected_grad)
+ assert len(calls) == 2
+
+ @pytest.mark.parametrize("layout", ["transposed", "channels_last", "sliced"])
+ def test_strided_logits_match_log_softmax(self, monkeypatch, layout, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ if layout == "transposed":
+ logits, labels = logits.transpose(-1, -2), labels.transpose(-1, -2)
+ elif layout == "channels_last":
+ logits = logits.contiguous(memory_format=torch.channels_last)
+ else:
+ logits = torch.cat([logits, logits], dim=1)[:, ::2]
+ expected, expected_grad = _reference(monkeypatch, logits, labels, 0.25, 2.0, "mean")
+ actual, grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ self.assert_close(actual, expected)
+ self.assert_close_scaled(grad, expected_grad)
+ # Contiguous, as the log_softmax path's gather backward makes it.
+ assert grad.stride() == expected_grad.stride()
+
+ @pytest.mark.parametrize("reduction", ["mean", "sum"])
+ @pytest.mark.parametrize("ignore_index", [None, -100])
+ def test_non_finite_logits_match_log_softmax(self, monkeypatch, reduction, ignore_index, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype, ignore_index=None)
+ big = 0.75 * torch.finfo(dtype).max
+ # (pixel row, class, value): +inf, -inf and NaN logits, a pixel of -inf only, and the #5628 overflow of a
+ # finite non-target logit gap, each on a pixel that is labelled and, with an ignore index, on one that is not.
+ cases = [(0, 3, float("inf")), (1, 5, float("-inf")), (2, 7, float("nan")), (4, 0, big), (4, 1, -big)]
+ for row, cls, value in cases:
+ logits[0, cls, row, :2] = value
+ logits[0, :, 3, :2] = float("-inf")
+ if ignore_index is not None:
+ labels[0, :, 1] = ignore_index
+ for reduction_logits in (logits, logits.nan_to_num(nan=0.0, posinf=0.0, neginf=0.0)):
+ expected, expected_grad = _reference(monkeypatch, reduction_logits, labels, 0.25, 2.0, reduction)
+ actual, grad = _value_and_grad(reduction_logits, labels, 0.25, 2.0, reduction)
+ self.assert_close_with_nan(actual, expected)
+ self.assert_close_with_nan(grad, expected_grad)
+ assert torch.equal(grad.isinf(), expected_grad.isinf())
+ if ignore_index is not None:
+ # A position that is not labelled gets an exact zero gradient, whatever its logits.
+ assert (grad[0, :, :, 1] == 0).all()
+
+ def test_ignored_non_finite_logits_have_zero_gradient_and_loss(self, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype, ignore_index=None)
+ labels[1] = -100
+ safe = logits.clone()
+ logits[1, :, :, ::3] = float("inf")
+ logits[1, :, :, 1::3] = float("nan")
+ logits[1, :, :, 2::3] = float("-inf")
+ expected, expected_grad = _value_and_grad(safe, labels, 0.25, 2.0, "sum")
+ actual, grad = _value_and_grad(logits, labels, 0.25, 2.0, "sum")
+ self.assert_close(actual, expected)
+ assert (grad[1] == 0).all()
+ self.assert_close_scaled(grad, expected_grad)
+
+ def test_chunks_and_functional_form_are_bitwise_equal(self, monkeypatch, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs((5, 21, 128, 128), device, dtype)
+ expected, expected_grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ assert focal_module._batch_chunks(logits)[0][0].shape[0] < 5
+ # One chunk for the whole batch, and the out-of-place form torch.compile and functorch trace.
+ monkeypatch.setattr(focal_module, "_CPU_CHUNK_BYTES", 1 << 40)
+ actual, grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ assert torch.equal(actual, expected)
+ assert torch.equal(grad, expected_grad)
+ monkeypatch.setattr(focal_module, "is_compiling", lambda: True)
+ actual, grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ assert torch.equal(actual, expected)
+ assert torch.equal(grad, expected_grad)
+
+ def test_gradcheck(self, monkeypatch, device):
+ _require_native_cpu(device, torch.float64)
+ monkeypatch.setattr(focal_module, "_CPU_MIN_NUMEL", 0)
+ monkeypatch.setattr(focal_module, "_CPU_CHUNK_BYTES", 1)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs((3, 4, 3, 2), device, torch.float64)
+ for gamma in (0.5, 2.0):
+ self.gradcheck(
+ focal_loss, (logits, labels, 0.25, gamma, "mean"), dtypes=[torch.float64, torch.int64, None, None, None]
+ )
+ assert calls
+
+ def test_gradgradcheck(self, monkeypatch, device):
+ # A double backward differentiates the backward: it recomputes the softmax from the logits.
+ _require_native_cpu(device, torch.float64)
+ monkeypatch.setattr(focal_module, "_CPU_MIN_NUMEL", 0)
+ calls = _count_calls(monkeypatch)
+ logits, labels = _inputs((3, 4, 3, 2), device, torch.float64)
+ logits.requires_grad_()
+ assert torch.autograd.gradgradcheck(lambda x: focal_loss(x, labels, 0.25, 2.0, "sum"), (logits,))
+ assert calls
+
+ def test_second_derivatives_match_log_softmax(self, monkeypatch, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ direction = torch.randn_like(logits)
+
+ def hessian_vector_product():
+ x = logits.detach().clone().requires_grad_()
+ (grad,) = torch.autograd.grad(focal_loss(x, labels, 0.25, 2.0, "mean"), x, create_graph=True)
+ return grad, torch.autograd.grad((grad * direction).sum(), x)[0]
+
+ actual = hessian_vector_product()
+ with monkeypatch.context() as patch:
+ patch.setattr(focal_module, "_focal_loss_cpu_eligible", lambda pred: False)
+ expected = hessian_vector_product()
+ self.assert_close_scaled(actual[0], expected[0])
+ self.assert_close_scaled(actual[1], expected[1])
+
+ @pytest.mark.parametrize("mode", ["jvp", "forward_over_reverse"])
+ def test_forward_mode_ad_keeps_log_softmax(self, monkeypatch, mode, device, dtype):
+ # A custom jvp breaks every compiled training graph (Dynamo cannot capture it), and a jvp built on the saved
+ # statistics gives wrong reverse-over-forward derivatives, so dual logits keep log_softmax.
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ tangent = torch.randn_like(logits)
+
+ def run():
+ x = logits.detach().clone().requires_grad_()
+ with torch.autograd.forward_ad.dual_level():
+ dual = torch.autograd.forward_ad.make_dual(x, tangent)
+ loss = focal_loss(dual, labels, 0.25, 2.0, "mean")
+ if mode == "jvp":
+ return torch.autograd.forward_ad.unpack_dual(loss)
+ (grad,) = torch.autograd.grad(loss, dual)
+ return torch.autograd.forward_ad.unpack_dual(grad)
+
+ calls = _count_calls(monkeypatch)
+ actual = run()
+ assert calls == []
+ with monkeypatch.context() as patch:
+ patch.setattr(focal_module, "_focal_loss_cpu_eligible", lambda pred: False)
+ expected = run()
+ assert torch.equal(actual.primal, expected.primal)
+ assert torch.equal(actual.tangent, expected.tangent)
+
+ def test_dual_and_batched_incoming_gradients(self, monkeypatch, device, dtype):
+ # Gradients that cannot be written into one plain buffer: a dual cotangent (forward-over-reverse) and the
+ # batched cotangents of is_grads_batched (legacy vmap, used by gradcheck and autograd.functional).
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ monkeypatch.setattr(focal_module, "_CPU_CHUNK_BYTES", 1) # one sample per chunk
+ calls = _count_calls(monkeypatch)
+ _, grad = _reference(monkeypatch, logits, labels, 0.25, 2.0, "sum")
+ x = logits.detach().clone().requires_grad_()
+ with torch.autograd.forward_ad.dual_level():
+ cotangent = torch.autograd.forward_ad.make_dual(
+ torch.ones((), device=device, dtype=dtype), torch.full((), 3.0, device=device, dtype=dtype)
+ )
+ (dual,) = torch.autograd.grad(focal_loss(x, labels, 0.25, 2.0, "sum"), x, cotangent)
+ self.assert_close_scaled(torch.autograd.forward_ad.unpack_dual(dual).tangent, 3 * grad)
+ x = logits.detach().clone().requires_grad_()
+ cotangents = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ (batched,) = torch.autograd.grad(focal_loss(x, labels, 0.25, 2.0, "sum"), x, cotangents, is_grads_batched=True)
+ self.assert_close_scaled(batched, torch.stack([grad, 2 * grad]))
+ assert len(calls) == 2
+
+ def test_retain_graph_second_backward(self, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ logits.requires_grad_()
+ loss = focal_loss(logits, labels, 0.25, 2.0, "mean")
+ (first,) = torch.autograd.grad(loss, logits, retain_graph=True)
+ (second,) = torch.autograd.grad(loss, logits)
+ assert torch.equal(first, second)
+
+ def test_module_and_backward_to_leaf(self, monkeypatch, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ expected, expected_grad = _reference(monkeypatch, logits, labels, 0.25, 2.0, "mean")
+ leaf = logits.clone().requires_grad_()
+ loss = FocalLoss(0.25, 2.0, "mean")(leaf, labels)
+ loss.backward()
+ self.assert_close(loss.detach(), expected)
+ self.assert_close_scaled(leaf.grad, expected_grad)
+
+ def test_vmap_has_no_user_warning(self, device, dtype):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ with warnings.catch_warnings(record=True) as recorded:
+ warnings.simplefilter("always")
+ actual = torch.vmap(lambda x, y: focal_loss(x[None], y[None], 0.25, 2.0, "mean"))(logits, labels)
+ assert not [w for w in recorded if issubclass(w.category, UserWarning)]
+ expected = torch.stack([focal_loss(x[None], y[None], 0.25, 2.0, "mean") for x, y in zip(logits, labels)])
+ self.assert_close(actual, expected)
+
+ def test_scripted_loss_matches(self, device, dtype):
+ # TorchScript compiles focal_loss without the custom function: its branch is a static `is_scripting` if.
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", FutureWarning)
+ scripted = torch.jit.script(focal_loss)
+ self.assert_close(scripted(logits, labels, 0.25, 2.0, "mean"), focal_loss(logits, labels, 0.25, 2.0, "mean"))
+
+ # The name keeps "compile" and "dynamo" out, so the ordinary jobs run it.
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_training_call_traces_in_one_graph(self, device, dtype):
+ # Logits that require grad: Dynamo rejects an autograd function that defines a jvp ("Unsupported custom jvp").
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ expected, expected_grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ torch._dynamo.reset()
+ compiled = torch.compile(focal_loss, backend="eager", fullgraph=True)
+ x = logits.detach().clone().requires_grad_()
+ actual = compiled(x, labels, 0.25, 2.0, "mean")
+ (grad,) = torch.autograd.grad(actual, x)
+ self.assert_close(actual, expected)
+ self.assert_close_scaled(grad, expected_grad)
+
+ def test_dynamo_on_an_eligible_input(self, device, dtype, torch_optimizer):
+ _require_native_cpu(device, dtype)
+ logits, labels = _inputs(LARGE, device, dtype)
+ expected, expected_grad = _value_and_grad(logits, labels, 0.25, 2.0, "mean")
+ compiled = torch_optimizer(focal_loss)
+ x = logits.detach().clone().requires_grad_()
+ actual = compiled(x, labels, 0.25, 2.0, "mean")
+ (grad,) = torch.autograd.grad(actual, x)
+ self.assert_close(actual, expected)
+ self.assert_close_scaled(grad, expected_grad)
+
+
+class _Exportable(torch.nn.Module):
+ def forward(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ return focal_loss(logits, labels, 0.25, 2.0, "mean")
+
+
[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+class TestFocalLossCpuExport(BaseTester):
+ # torch.export keeps log_softmax: the CPU path's size check would become a guard of the exported program, which
+ # then fails at run time for logits on the other side of the threshold although its dynamic shapes allow them.
+ @pytest.mark.parametrize(
+ "example, other", [((2, 21, 128, 128), (3, 21, 8, 12)), ((2, 21, 8, 8), (3, 21, 160, 170))]
+ )
+ def test_dynamic_sizes_run_on_both_sides_of_the_threshold(self, example, other, device, dtype):
+ _require_native_cpu(device, dtype)
+ dim = torch.export.Dim
+ batch, height, width = dim("B", min=1, max=64), dim("H", min=2, max=4096), dim("W", min=2, max=4096)
+ dynamic = {"logits": {0: batch, 2: height, 3: width}, "labels": {0: batch, 1: height, 2: width}}
+ program = torch.export.export(_Exportable(), _inputs(example, device, dtype), dynamic_shapes=dynamic)
+ assert any(node.target == torch.ops.aten.log_softmax.int for node in program.graph.nodes)
+ exported = program.module()
+ for shape in (example, other):
+ logits, labels = _inputs(shape, device, dtype)
+ self.assert_close(exported(logits, labels), focal_loss(logits, labels, 0.25, 2.0, "mean"))