Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): compiled focal_loss raises on out-of-range CPU labels instead of aborting the process (#6104)

Dmytro Mishkin64478eab87ab
diff --git a/changelog.d/6104.fixed.md b/changelog.d/6104.fixed.md
new file mode 100644
index 000000000..54263ed5c
--- /dev/null
+++ b/changelog.d/6104.fixed.md
@@ -0,0 +1,11 @@
+`focal_loss` and `FocalLoss` raise a `RuntimeError` for a label outside the classes under `torch.compile` on the CPU, as
+they do in eager mode. With `reduction='mean'` or `'sum'` and no `weight`, the loss gathers the target class, and
+Inductor's CPU gather checks its indices inside an OpenMP parallel region: a label past the classes terminated the whole
+Python process (exit code 134, "index out of bounds") on torch 2.5.1, 2.9.1 and 2.14, a negative label did the same on
+2.14, and 2.5.1 and 2.9.1 returned a loss for a negative label when no gradient was needed. The labels are now checked
+with `torch._assert_async` before the gather, and on torch 2.14 a compiled gather reads them clamped into range, so it
+stays in bounds until the check raises. Inductor before torch 2.9 compiles the assert to nothing, so there a compiled
+call still fails as before. The check uses `one_hot`'s messages: an eager CPU call now raises "Class values must be
+non-negative." or "Class values must be smaller than num_classes." where the gather raised "index ... is out of bounds
+for dimension 1 with size C", as the `'none'` and weighted losses already did. CUDA is unchanged: an out-of-range label
+still fails the gather's device-side assert there.
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 07b059edd..729605b9f 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -24,7 +24,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.losses._utils import mask_ignore_pixels
-from kornia.losses.one_hot import one_hot
+from kornia.losses.one_hot import _check_class_labels, one_hot
# based on:
# https://github.com/zhezh/focalloss/blob/master/focalloss.py
@@ -124,6 +124,8 @@ def focal_loss(
if reduced:
KORNIA_CHECK(target.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {target.dtype}")
KORNIA_CHECK(pred.shape[1] >= 1, f"The number of classes must be >= 1. Got pred of shape {pred.shape}")
+ # one_hot's errors before the gather below, whose compiled CPU kernel aborts on a label outside the classes.
+ target = _check_class_labels(target, pred.shape[1])
else:
target_one_hot = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index 3095943cd..ae0ad7400 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -18,7 +18,12 @@
import torch
import torch.nn.functional as F
+from kornia.core._compat import torch_version_ge
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
+from kornia.core.utils import is_compiling, is_exporting
+
+# Inductor lowers torch._assert_async to a runtime check from torch 2.9.0; up to 2.8 it decomposes it to nothing.
+_INDUCTOR_KEEPS_ASSERT_ASYNC = torch_version_ge(2, 9)
def one_hot(
@@ -84,3 +89,48 @@ def one_hot(
# Optional smoothing floor: the zeros become eps and the ones stay 1
return one_hot_tensor * (1.0 - eps) + eps
+
+
+def _check_class_labels(labels: torch.Tensor, num_classes: int) -> torch.Tensor:
+ """Raise :func:`one_hot`'s errors for CPU labels outside ``[0, num_classes)``, eager and compiled alike.
+
+ For a loss that gathers, scatters or indexes with the labels instead of building a one-hot target: index with the
+ labels it returns. Inductor's CPU kernel for such an op checks each index inside an OpenMP parallel region, where a
+ failed check cannot propagate, so an out-of-range label terminates the process (``index out of bounds``, exit code
+ 134) instead of raising the eager op's ``RuntimeError``. ``torch._assert_async`` raises a ``RuntimeError`` on the
+ CPU, at once in eager code and from the compiled kernel that evaluates it, without a graph break.
+
+ Inductor may fuse the asserts into the index op's kernel and evaluate them after its parallel loop, so under
+ ``torch.compile`` the labels come back clamped into range: the index op stays in bounds until the asserts raise.
+ They stay unclamped where the asserts may not survive, so that the index op fails instead of a wrong loss being
+ returned: before torch 2.9, whose Inductor compiles the assert to nothing, and in an exported graph, which ONNX
+ translates without it. torch 2.9.1 reports a ``torch.compile`` capture as an export too; its Inductor ran the
+ asserts first in every case checked.
+
+ Only CPU labels are checked: on CUDA the index kernels fail an out-of-range label with a device-side assert in
+ eager and compiled code alike, and so would this assert. Functorch transforms skip it, since ``vmap`` has no
+ batching rule for the assert, and so does TorchScript, whose scripted and traced graphs drop the assert anyway;
+ the index op raises its own ``RuntimeError`` there.
+
+ Args:
+ labels: int64 class labels of any shape; labels to ignore must already be replaced by a valid class.
+ num_classes: the number of classes.
+
+ Returns:
+ ``labels``, clamped to ``[0, num_classes - 1]`` in a CPU ``torch.compile`` capture that is not an export,
+ from torch 2.9 on.
+ """
+ if labels.device.type != "cpu":
+ return labels
+ if not torch.jit.is_scripting(): # TorchScript only skips a bare is_scripting() guard
+ if torch._C._are_functorch_transforms_active():
+ return labels
+ # One pass for both bounds (a quarter of the eager cost of two comparisons and two all()); aminmax rejects an
+ # empty tensor, which holds no label to check. An explicit dimension lets ONNX lower the reduction too.
+ if labels.numel() > 0:
+ low, high = torch.aminmax(labels.reshape(-1), dim=0)
+ torch._assert_async(low >= 0, "Class values must be non-negative.")
+ torch._assert_async(high < num_classes, "Class values must be smaller than num_classes.")
+ if _INDUCTOR_KEEPS_ASSERT_ASYNC and is_compiling() and not is_exporting():
+ return labels.clamp(0, num_classes - 1)
+ return labels
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index b972d31ad..2c07ab36a 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -15,14 +15,22 @@
# limitations under the License.
#
+import importlib
+import subprocess
+import sys
+from pathlib import Path
+
import pytest
import torch
import torch.nn.functional as F
import kornia
+from kornia.core.utils import is_exporting
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+one_hot_module = importlib.import_module("kornia.losses.one_hot")
+
class TestBinaryFocalLossWithLogits(BaseTester):
@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
@@ -524,6 +532,57 @@ class TestFocalLoss(BaseTester):
self.assert_close(values[off_class], torch.zeros_like(values[off_class]), rtol=0, atol=0)
assert (values[~off_class] > 0).all()
+ @pytest.mark.parametrize("reduction, weighted", [("mean", False), ("sum", False), ("mean", True), ("none", False)])
+ @pytest.mark.parametrize("ignore_index", [-100, None])
+ def test_exception_labels_outside_the_classes(self, device, dtype, reduction, weighted, ignore_index):
+ # Unweighted 'mean' and 'sum' gather the target class, the others build a one-hot target: both raise
+ # one_hot's errors. The gather used to raise its own "index ... is out of bounds".
+ if device.type != "cpu":
+ pytest.skip("an out-of-range index fails a device-side assert off the CPU, which ends the CUDA context")
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 4, device=device, dtype=dtype)
+ weight = torch.ones(num_classes, device=device, dtype=dtype) if weighted else None
+ for value, message in ((num_classes, "smaller than num_classes"), (-3, "non-negative")):
+ labels = torch.randint(num_classes, (2, 4), device=device)
+ labels[0, 1] = value
+ with pytest.raises(RuntimeError, match=f"Class values must be {message}"):
+ kornia.losses.focal_loss(logits, labels, 0.25, 2.0, reduction, weight, ignore_index)
+
+ # The name keeps "compile" and "dynamo" out, so the ordinary jobs run it.
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("reduction", ["mean", "sum"])
+ def test_reduced_label_check_traces_in_one_graph(self, device, dtype, reduction):
+ # The label check of the gather path is captured with the loss, in one graph, and raises when it runs.
+ if device.type != "cpu":
+ pytest.skip("the label check runs on the CPU only")
+ graphs = []
+
+ def backend(gm, example_inputs):
+ graphs.append(gm)
+ return gm.forward
+
+ logits = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ labels = torch.randint(3, (2, 4), device=device)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.losses.focal_loss, backend=backend, fullgraph=True)
+ expected = kornia.losses.focal_loss(logits, labels, 0.25, 2.0, reduction)
+ self.assert_close(compiled(logits, labels, 0.25, 2.0, reduction), expected)
+ assert len(graphs) == 1
+ nodes = graphs[0].graph.nodes
+ assert sum(node.target is torch._assert_async for node in nodes) == 2
+ # Compiled from torch 2.9 on, the gather reads clamped labels, in bounds in whatever order Inductor runs the
+ # asserts. They stay unclamped where a torch.compile capture also reports an export (torch 2.9.1).
+ index = next(node for node in nodes if node.target == "gather").args[2]
+ while index.target == "unsqueeze":
+ index = index.args[0]
+ assert (index.target == "clamp") == (
+ one_hot_module._INDUCTOR_KEEPS_ASSERT_ASYNC and not _compile_reports_export()
+ )
+ labels[0, 1] = 3
+ with pytest.raises(RuntimeError, match="Class values must be smaller than num_classes"):
+ compiled(logits, labels, 0.25, 2.0, reduction)
+ assert len(graphs) == 1
+
@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
def test_dynamo(self, device, dtype, torch_optimizer, reduction):
num_classes = 3
@@ -573,6 +632,76 @@ class TestFocalLoss(BaseTester):
self.assert_close(op_module(logits, labels), op(logits, labels, *args))
+def _compile_reports_export() -> bool:
+ # Some releases (2.5.1 and 2.9.1 checked) also report a torch.compile capture as an export.
+ probe = torch.compile(lambda x: x + float(is_exporting()), backend="eager", fullgraph=True)
+ return bool(probe(torch.zeros(())) > 0)
+
+
+# Run in a fresh interpreter: an index check that fails inside an Inductor CPU kernel aborts the whole process.
+_COMPILED_INVALID_LABEL = """
+import sys, warnings
+warnings.filterwarnings("ignore")
+import torch, kornia
+reduction, ignore_index, value, requires_grad = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] == "1"
+generator = torch.Generator().manual_seed(0)
+pred = torch.randn(2, 21, 128, 128, generator=generator).requires_grad_(requires_grad)
+target = torch.randint(0, 21, (2, 128, 128), generator=generator)
+target[0, 5, 7] = value
+loss = torch.compile(kornia.losses.focal_loss, fullgraph=True)
+try:
+ out = loss(pred, target, 0.25, 2.0, reduction, None, None if ignore_index == "None" else int(ignore_index))
+ if requires_grad:
+ out.backward()
+except RuntimeError as error:
+ print("RuntimeError:", error)
+else:
+ print("no error")
+"""
+
+
[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+class TestFocalLossCompiledLabels(BaseTester):
+ @pytest.mark.parametrize(
+ "reduction, ignore_index, requires_grad", [("mean", -100, False), ("mean", -100, True), ("sum", None, False)]
+ )
+ @pytest.mark.parametrize("value, message", [(21, "smaller than num_classes"), (-3, "non-negative")])
+ def test_dynamo_invalid_label_raises(
+ self, reduction, ignore_index, requires_grad, value, message, device, dtype, optimizer_backend
+ ):
+ # Compiled, the target-class gather of 'mean' and 'sum' terminated the process (exit code 134, "index out of
+ # bounds") where eager raises: for a label past the classes on torch 2.5.1, 2.9.1 and 2.14, and for a
+ # negative one on 2.14; 2.5.1 and 2.9.1 returned a loss for it without gradients. The check does not depend
+ # on is_exporting(), which a torch.compile capture also reports on 2.5.1 and 2.9.1, so 2.9.1 runs it too.
+ if device.type != "cpu" or dtype != torch.float32 or optimizer_backend != "inductor":
+ pytest.skip("one fresh-process inductor compile per case, on the CPU in float32")
+ from torch._inductor.decomposition import decompositions
+
+ if torch.ops.aten._assert_async.msg in decompositions:
+ pytest.skip("this torch release's Inductor compiles torch._assert_async to nothing (before torch 2.9)")
+ # The checkout under test, which "-c" imports first from the working directory.
+ root = Path(kornia.__file__).resolve().parents[1]
+ result = subprocess.run( # noqa: S603 - this interpreter and a literal program; no shell or external input.
+ [
+ sys.executable,
+ "-c",
+ _COMPILED_INVALID_LABEL,
+ reduction,
+ str(ignore_index),
+ str(value),
+ str(int(requires_grad)),
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=900,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr[-2000:]
+ assert result.stdout.startswith("RuntimeError:"), result.stdout
+ assert f"Class values must be {message}" in result.stdout
+
+
class TestConventionsFocalLoss(BaseTester):
"""Pins for the class weighting, reductions, ignored labels and known defect of the focal losses."""
diff --git a/tests/losses/test_one_hot.py b/tests/losses/test_one_hot.py
index 0e27ce027..7be26e050 100644
--- a/tests/losses/test_one_hot.py
+++ b/tests/losses/test_one_hot.py
@@ -16,15 +16,20 @@
#
import math
+import subprocess
+import sys
+from pathlib import Path
import pytest
import torch
import torch.nn.functional as F
+from torch.fx.experimental.proxy_tensor import make_fx
+import kornia
from kornia.core.exceptions import BaseError
-from kornia.losses.one_hot import one_hot
+from kornia.losses.one_hot import _INDUCTOR_KEEPS_ASSERT_ASYNC, _check_class_labels, one_hot
-from testing.base import BaseTester, assert_close
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, assert_close, dynamo_is_available
class TestOneHot:
@@ -101,6 +106,121 @@ class TestOneHot:
torch.jit.script(one_hot)(labels, 3, device, torch.int64, 0.125)
+# Run in a fresh interpreter: an index check that fails inside an Inductor CPU kernel aborts the whole process. The
+# target-class focal loss of masked logits, as a custom log-softmax computes it: torch 2.14's Inductor fuses the gather
+# into a parallel loop that runs before the label asserts, so unclamped labels terminated the process here.
+_COMPILED_GATHER_BEFORE_THE_ASSERTS = """
+import sys, warnings
+warnings.filterwarnings("ignore")
+import torch
+from kornia.losses.one_hot import _check_class_labels
+value = int(sys.argv[1])
+
+def loss(pred, target):
+ valid = (target != -100).unsqueeze(1)
+ target = _check_class_labels(torch.where(target != -100, target, 0), pred.shape[1]).unsqueeze(1)
+ x = torch.where(valid, pred, 0.0)
+ x_max = x.amax(1, keepdim=True)
+ log_prob = (x.gather(1, target) - x_max) - (x - x_max).exp().sum(1, keepdim=True).log()
+ base = 1.0 - log_prob.exp()
+ weight = torch.where(base == 0, base.pow(2.0), base.masked_fill(base == 0, 1.0).pow(2.0))
+ term = -weight * log_prob.masked_fill(~valid, 0.0)
+ term = torch.where(target == 0, term.new_full((), 0.75), term.new_full((), 0.25)) * term
+ return term.mean() / pred.shape[1]
+
+generator = torch.Generator().manual_seed(0)
+pred = torch.randn(2, 21, 128, 128, generator=generator)
+target = torch.randint(0, 21, (2, 128, 128), generator=generator)
+target[0, 5, 7] = value
+try:
+ torch.compile(loss, fullgraph=True)(pred, target)
+except RuntimeError as error:
+ print("RuntimeError:", error)
+else:
+ print("no error")
+"""
+
+
+class TestCheckClassLabels(BaseTester):
+ def test_valid_labels_pass_unchanged(self, device, dtype):
+ labels = torch.tensor([[0, 2, 1], [2, 2, 0]], device=device)
+ assert _check_class_labels(labels, 3) is labels
+ empty = torch.zeros(0, 3, device=device, dtype=torch.int64)
+ assert _check_class_labels(empty, 3) is empty
+
+ def test_exception(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip("only CPU labels are checked")
+ for value, message in ((3, "smaller than num_classes"), (-1, "non-negative")):
+ labels = torch.tensor([[0, 2, 1], [2, value, 0]], device=device)
+ with pytest.raises(RuntimeError, match=f"Class values must be {message}"):
+ _check_class_labels(labels, 3)
+
+ @pytest.mark.device_agnostic
+ def test_other_devices_and_vmap_skip_the_check(self, device, dtype):
+ # A meta tensor stands for any device but the CPU on every leg, and vmap has no batching rule for the assert.
+ def asserts(labels):
+ graph = make_fx(lambda x: _check_class_labels(x, 3))(labels).graph
+ return sum(node.target is torch.ops.aten._assert_async.msg for node in graph.nodes)
+
+ assert asserts(torch.zeros(2, 3, dtype=torch.int64)) == 2
+ labels = torch.full((2, 3), 7, device="meta", dtype=torch.int64)
+ assert asserts(labels) == 0
+ assert _check_class_labels(labels, 3) is labels
+ bad = torch.tensor([[0, 3], [1, 2]])
+ assert torch.equal(torch.func.vmap(lambda x: _check_class_labels(x, 3))(bad), bad)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_version_gate_matches_inductor(self, device, dtype):
+ # Compiled labels are clamped only where Inductor keeps the asserts; up to torch 2.8 it decomposes them away.
+ from torch._inductor.decomposition import decompositions
+
+ assert _INDUCTOR_KEEPS_ASSERT_ASYNC == (torch.ops.aten._assert_async.msg not in decompositions)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_export_keeps_the_labels_unclamped(self, device, dtype):
+ # ONNX translates an exported graph without its asserts, where clamped labels would turn the failing index op
+ # into a silent wrong value. The exported program itself keeps the asserts.
+ class _Gather(torch.nn.Module):
+ def forward(self, x: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ return x.gather(1, _check_class_labels(labels, x.shape[1]).unsqueeze(1))
+
+ x = torch.rand(2, 3, 4)
+ labels = torch.randint(3, (2, 4))
+ exported = torch.export.export(_Gather(), (x, labels))
+ targets = [str(node.target) for node in exported.graph.nodes]
+ assert not any("clamp" in target for target in targets)
+ assert sum("_assert_async" in target for target in targets) == 2
+ labels[0, 1] = 3
+ with pytest.raises(RuntimeError, match="Class values must be smaller than num_classes"):
+ exported.module()(x, labels)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("value, message", [(21, "smaller than num_classes"), (-3, "non-negative")])
+ def test_dynamo_gather_fused_before_the_asserts_raises(self, value, message, device, dtype, optimizer_backend):
+ if device.type != "cpu" or dtype != torch.float32 or optimizer_backend != "inductor":
+ pytest.skip("one fresh-process inductor compile per case, on the CPU in float32")
+ from torch._inductor.decomposition import decompositions
+
+ if torch.ops.aten._assert_async.msg in decompositions:
+ pytest.skip("this torch release's Inductor compiles torch._assert_async to nothing (before torch 2.9)")
+ # The checkout under test, which "-c" imports first from the working directory.
+ root = Path(kornia.__file__).resolve().parents[1]
+ result = subprocess.run( # noqa: S603 - this interpreter and a literal program; no shell or external input.
+ [sys.executable, "-c", _COMPILED_GATHER_BEFORE_THE_ASSERTS, str(value)],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=900,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr[-2000:]
+ assert result.stdout.startswith("RuntimeError:"), result.stdout
+ assert f"Class values must be {message}" in result.stdout
+
+
class TestConventionsOneHot(BaseTester):
"""Pins for the layout of :func:`kornia.losses.one_hot`."""
diff --git a/tests/onnx/test_export_coverage.py b/tests/onnx/test_export_coverage.py
index ee9367ab5..d484fe0ad 100644
--- a/tests/onnx/test_export_coverage.py
+++ b/tests/onnx/test_export_coverage.py
@@ -191,6 +191,15 @@ def test_onnx_export_matches_eager(module, inputs):
_assert_same(eager, ort_out)
[email protected]("reduction", ["mean", "sum"])
+def test_focal_loss_export(reduction):
+ # The CPU label check's aminmax must lower through ONNX, not only through torch.export.
+ logits = torch.linspace(-2.0, 2.0, 24).reshape(2, 3, 4)
+ labels = torch.tensor([[0, 1, 2, -100], [2, 0, 1, 2]])
+ eager, ort_out = _export_and_run(kornia.losses.FocalLoss(alpha=0.25, reduction=reduction), (logits, labels))
+ _assert_same(eager, ort_out)
+
+
def test_boxes_to_mask_export():
boxes = kornia.geometry.boxes.Boxes(torch.tensor([[[[1.0, 1.0], [5.0, 1.0], [5.0, 4.0], [1.0, 4.0]]]]))