Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: accept empty batches where reshape/view(B, -1) flattened the batch (#6266 group A) (#6238)

Viranshul-Pd8bff0630ee9
diff --git a/changelog.d/6238.fixed.md b/changelog.d/6238.fixed.md
new file mode 100644
index 000000000..2d0e092cb
--- /dev/null
+++ b/changelog.d/6238.fixed.md
@@ -0,0 +1,6 @@
+Functions that flattened a batch with `reshape(B, -1)` or `view(B, -1)` now accept empty batches instead of raising
+"cannot reshape tensor of 0 elements" (#6266, group A): the 2D and 3D mutual-information losses and their `FromRef`
+modules, `lovasz_softmax_loss`, `lovasz_hinge_loss` and their modules, `determinant_to_polynomial`, `ALIKED`,
+`XFeatModel` and `LoFTR`. `XFeat.detectAndCompute` returns an empty list and `XFeat.match_xfeat_star` an empty list of
+matches for an empty batch. `determinant_to_polynomial` also accepts a non-contiguous input, which raised "view size is
+not compatible". A mutual-information signal with no samples raises a clear error instead of an `IndexError`.
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index a70dbeeb5..caab70a77 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -284,21 +284,21 @@ class DKD(nn.Module):
if self.top_k > 0:
# at most top_k of the maxima: a non-maximum scores -inf here and is dropped, not used to fill up to top_k
- candidate_scores = scores_nograd.masked_fill(~is_max, float("-inf")).reshape(b, -1)
+ candidate_scores = scores_nograd.masked_fill(~is_max, float("-inf")).flatten(start_dim=1)
topk = torch.topk(candidate_scores, min(self.top_k, h * w))
indices_keypoints = [topk.indices[i][topk.values[i] > float("-inf")] for i in range(b)]
else:
# the per-image mean score: the threshold when scores_th <= 0, and the fallback of an image whose maxima
# are all at or below scores_th, decided for each image alone
- mean = scores_nograd.reshape(b, -1).mean(dim=1).reshape(b, 1, 1, 1)
+ mean = scores_nograd.flatten(start_dim=1).mean(dim=1).reshape(b, 1, 1, 1)
masks = is_max & (scores_nograd > mean)
if self.scores_th > 0:
above = is_max & (scores_nograd > self.scores_th)
- masks = torch.where(above.reshape(b, -1).any(dim=1).reshape(b, 1, 1, 1), above, masks)
- masks = masks.reshape(b, -1)
+ masks = torch.where(above.flatten(start_dim=1).any(dim=1).reshape(b, 1, 1, 1), above, masks)
+ masks = masks.flatten(start_dim=1)
indices_keypoints = []
- scores_view = scores_nograd.reshape(b, -1)
+ scores_view = scores_nograd.flatten(start_dim=1)
for mask, scores in zip(masks, scores_view):
indices = mask.nonzero()[:, 0]
if len(indices) > self.n_limit:
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index dbaf6569b..3fc509d0a 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -256,12 +256,10 @@ class LoFTR(nn.Module):
# Token-major copies: the reshape of the permuted maps is a channel-strided view, and every transformer GEMM
# on it would run on the transposed layout.
feat_c0 = feat_c0.permute(0, 2, 3, 1)
- n, _h, _w, c = feat_c0.shape
- feat_c0 = feat_c0.reshape(n, -1, c).contiguous()
+ feat_c0 = feat_c0.flatten(start_dim=1, end_dim=2).contiguous()
feat_c1 = feat_c1.permute(0, 2, 3, 1)
- n1, _h1, _w1, c1 = feat_c1.shape
- feat_c1 = feat_c1.reshape(n1, -1, c1).contiguous()
+ feat_c1 = feat_c1.flatten(start_dim=1, end_dim=2).contiguous()
mask_c0 = mask_c1 = None # mask is useful in training
# a coarse cell takes the mask value of the pixel it sits on
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index 252a8bd94..c85d017d7 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -73,15 +73,15 @@ class LoFTREncoderLayer(nn.Module):
source_mask: [N, S] (optional)
"""
- bs = x.size(0)
query, key, value = x, source, source
# multi-head attention
- query = self.q_proj(query).view(bs, -1, self.nhead, self.dim) # [N, L, (H, D)]
- key = self.k_proj(key).view(bs, -1, self.nhead, self.dim) # [N, S, (H, D)]
- value = self.v_proj(value).view(bs, -1, self.nhead, self.dim)
+ # unflatten and flatten split and merge the heads without a -1, which an empty batch cannot infer
+ query = self.q_proj(query).unflatten(-1, (self.nhead, self.dim)) # [N, L, (H, D)]
+ key = self.k_proj(key).unflatten(-1, (self.nhead, self.dim)) # [N, S, (H, D)]
+ value = self.v_proj(value).unflatten(-1, (self.nhead, self.dim))
message = self.attention(query, key, value, q_mask=x_mask, kv_mask=source_mask) # [N, L, (H, D)]
- message = self.merge(message.view(bs, -1, self.nhead * self.dim)) # [N, L, C]
+ message = self.merge(message.flatten(start_dim=-2)) # [N, L, C]
message = self.norm1(message)
# feed-forward network
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index 4fed6845c..9030d6de5 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -194,7 +194,7 @@ class XFeatModel(nn.Module):
"""Unfold spatial dims by window size ``ws`` and concatenate into channels."""
B, C, H, W = x.shape
x = x.unfold(2, ws, ws).unfold(3, ws, ws).reshape(B, C, H // ws, W // ws, ws**2)
- return x.permute(0, 1, 4, 2, 3).reshape(B, -1, H // ws, W // ws)
+ return x.permute(0, 1, 4, 2, 3).flatten(start_dim=1, end_dim=2)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run the XFeat backbone.
@@ -413,7 +413,7 @@ class XFeat(nn.Module):
B = x.shape[0]
pos = nms2d(x, (kernel_size, kernel_size), mask_only=True) & (x > threshold)
pos_batched = [k.nonzero()[..., 1:].flip(-1) for k in pos]
- pad_val = max(len(p) for p in pos_batched)
+ pad_val = max((len(p) for p in pos_batched), default=0) # an empty batch pads to no keypoints
pos_out = torch.full((B, pad_val, 2), -1, dtype=torch.long, device=x.device)
for b in range(B):
pos_out[b, : len(pos_batched[b])] = pos_batched[b]
@@ -498,8 +498,8 @@ class XFeat(nn.Module):
if top_k is None:
top_k = _H1 * _W1
xy1 = (self._create_xy(_H1, _W1, M1.device) * 8).expand(B, -1, -1)
- M1 = M1.permute(0, 2, 3, 1).reshape(B, -1, C)
- H1 = H1.permute(0, 2, 3, 1).reshape(B, -1)
+ M1 = M1.permute(0, 2, 3, 1).flatten(start_dim=1, end_dim=2)
+ H1 = H1.permute(0, 2, 3, 1).flatten(start_dim=1)
if top_k < 1:
return torch.zeros(B, 0, 2, device=M1.device), M1.new_zeros(B, 0, C)
_, top_k_idx = torch.topk(H1, k=min(H1.shape[1], top_k), dim=-1)
@@ -697,7 +697,8 @@ class XFeat(nn.Module):
top_k: number of top features to use.
Returns:
- If ``B > 1``: list of :math:`(N, 4)` tensors with ``(x1, y1, x2, y2)`` matches.
+ If ``B != 1``: list of :math:`(N, 4)` tensors with ``(x1, y1, x2, y2)`` matches, one per pair; an empty
+ batch gives an empty list.
If ``B == 1``: tuple of :math:`(N, 2)` matched keypoint tensors.
"""
if top_k is None:
@@ -707,6 +708,6 @@ class XFeat(nn.Module):
idxs_list = self._batch_match(out1["descriptors"], out2["descriptors"])
B = im_set1.shape[0]
matches = [self._refine_matches(out1, out2, matches=idxs_list, batch_idx=b) for b in range(B)]
- if B > 1:
+ if B != 1:
return matches
return matches[0][:, :2], matches[0][:, 2:]
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index f7a9ff3db..b99e2e06d 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -2921,7 +2921,7 @@ def determinant_to_polynomial(
signs = signs.to(device, dtype)
coefficient_map = coefficient_map.to(device)
- A_flat = A.view(B, -1)
+ A_flat = A.flatten(start_dim=1)
gathered_values = A_flat[:, multiplication_indices]
products = torch.prod(gathered_values, dim=-1)
signed_products = products * signs
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 868f899e1..d210ad91c 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -100,8 +100,8 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
# The labels, the Jaccard weights and the sum over pixels are accumulated in the prediction dtype, or in float32
# for a half-precision prediction, where pixel counts stay exact up to 2**24 pixels.
accumulation_dtype = torch.promote_types(pred.dtype, torch.float32)
- pred_flatten: Tensor = pred.reshape(pred.shape[0], -1)
- target_flatten: Tensor = target.reshape(target.shape[0], -1).to(accumulation_dtype)
+ pred_flatten: Tensor = pred.flatten(start_dim=1)
+ target_flatten: Tensor = target.flatten(start_dim=1).to(accumulation_dtype)
# get shapes
B, N = pred_flatten.shape
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index f7db9635f..044fa7281 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -117,9 +117,10 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
f"weight and pred must be in the same device. Got: {weight.device} and {pred.device}",
)
- # flatten pred [B, C, -1] and target [B, -1] and to float
- pred_flatten: Tensor = pred.reshape(pred.shape[0], pred.shape[1], -1)
- target_flatten: Tensor = target.reshape(target.shape[0], -1)
+ # flatten pred to [B, C, H*W] and target to [B, H*W]; flatten keeps an empty batch, where reshape(B, -1) cannot
+ # infer the -1
+ pred_flatten: Tensor = pred.flatten(start_dim=2)
+ target_flatten: Tensor = target.flatten(start_dim=1)
# get shapes
_, C, N = pred_flatten.shape
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index e6e114b9c..dcb36e403 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -211,6 +211,7 @@ class EntropyBasedLossBase(torch.nn.Module):
"num_bins must be an integer >= 2.",
)
KORNIA_CHECK(window_radius > 0, "window_radius must be > 0.")
+ KORNIA_CHECK(reference_signal.shape[-1] > 0, "signals must have at least one sample.")
if not isinstance(kernel_function, MIKernel):
raise ValueError(f"kernel_function must be a MIKernel member, the available options are {list(MIKernel)}.")
_validate_mask(mask, reference_signal.shape[-1:])
@@ -510,7 +511,7 @@ class MILossFromRef2D(MILossFromRef):
Tensor with shape :math:`(*, H * W)` suitable for histogram-based
mutual-information computation.
"""
- return tensor.reshape(tensor.shape[:-2] + (-1,))
+ return tensor.flatten(max(tensor.dim() - 2, 0))
def forward(
self,
@@ -598,7 +599,7 @@ class MILossFromRef3D(MILossFromRef):
Returns:
Tensor with shape :math:`(*, D * H * W)` for entropy estimation.
"""
- return tensor.reshape(tensor.shape[:-3] + (-1,))
+ return tensor.flatten(max(tensor.dim() - 3, 0))
def forward(
self,
@@ -685,7 +686,7 @@ class NMILossFromRef2D(NMILossFromRef):
Tensor with shape :math:`(*, H * W)` used by the normalized
mutual-information base implementation.
"""
- return tensor.reshape(tensor.shape[:-2] + (-1,))
+ return tensor.flatten(max(tensor.dim() - 2, 0))
def forward(
self,
@@ -772,7 +773,7 @@ class NMILossFromRef3D(NMILossFromRef):
Tensor with shape :math:`(*, D * H * W)` used by the normalized
mutual-information base implementation.
"""
- return tensor.reshape(tensor.shape[:-3] + (-1,))
+ return tensor.flatten(max(tensor.dim() - 3, 0))
def forward(
self,
diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.py
index fe5cb9bb2..3bf678967 100644
--- a/tests/feature/test_aliked.py
+++ b/tests/feature/test_aliked.py
@@ -244,6 +244,14 @@ class TestDeformConv2d(BaseTester):
class TestALIKED(BaseTester):
+ @pytest.mark.parametrize("top_k_mode", [False, True])
+ def test_empty_batch_6266(self, top_k_mode, dtype, device):
+ """An empty batch gives one ALIKEDFeatures per image: none, in threshold and in top-k mode."""
+ kwargs = {"detection_threshold": 0.0, "max_num_keypoints": 20} if top_k_mode else {}
+ aliked = ALIKED(model_name="aliked-t16", **kwargs).to(device, dtype).eval()
+ output = aliked(torch.rand(0, 3, 64, 64, device=device, dtype=dtype))
+ assert output == []
+
def test_smoke(self, dtype, device):
aliked = ALIKED().to(device, dtype).eval()
inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 3df59caa0..a7d57fa7c 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -319,6 +319,20 @@ class TestLoFTR(BaseTester):
for k, v in out.items():
self.assert_close(v, out_jit[k])
+ def test_empty_batch_6266(self, device, dtype):
+ """An empty batch flattens the coarse maps without a -1 to infer and returns no matches."""
+ loftr = _loftr_matching_every_cell(device, dtype)
+ out = loftr(
+ {
+ "image0": torch.rand(0, 1, 64, 64, device=device, dtype=dtype),
+ "image1": torch.rand(0, 1, 64, 64, device=device, dtype=dtype),
+ }
+ )
+ assert out["keypoints0"].shape == (0, 2)
+ assert out["keypoints1"].shape == (0, 2)
+ assert out["confidence"].shape == (0,)
+ assert out["batch_indexes"].shape == (0,)
+
class TestLoFTRConfigIsPerInstance(BaseTester):
"""Building a LoFTR must not write into ``default_cfg`` or into a caller-passed config."""
diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.py
index ab2a4ab1e..ec92e8e70 100644
--- a/tests/feature/test_xfeat.py
+++ b/tests/feature/test_xfeat.py
@@ -38,6 +38,14 @@ from testing.base import (
class TestXFeatModel(BaseTester):
+ def test_empty_batch_6266(self, device, dtype):
+ """An empty batch keeps every non-batch dimension of the three maps."""
+ model = XFeatModel().to(device, dtype).eval()
+ feats, keypoints, heatmap = model(torch.rand(0, 1, 64, 64, device=device, dtype=dtype))
+ assert feats.shape == (0, 64, 8, 8)
+ assert keypoints.shape == (0, 65, 8, 8)
+ assert heatmap.shape == (0, 1, 8, 8)
+
def test_smoke(self, device, dtype):
model = XFeatModel().to(device, dtype)
x = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
@@ -149,6 +157,17 @@ class TestInterpolateSparse2d(BaseTester):
class TestXFeat(BaseTester):
+ def test_empty_batch_6266(self, device, dtype):
+ """An empty batch gives no per-image results, an empty dense batch and no match lists."""
+ model = XFeat().to(device).eval()
+ x = torch.rand(0, 3, 64, 64, device=device)
+ assert model.detectAndCompute(x, top_k=50) == []
+ dense = model.detectAndComputeDense(x, top_k=50)
+ assert dense["keypoints"].shape == (0, 50, 2)
+ assert dense["descriptors"].shape == (0, 50, 64)
+ assert dense["scales"].shape == (0, 50)
+ assert model.match_xfeat_star(x, x, top_k=50) == []
+
def test_smoke(self, device, dtype):
model = XFeat().to(device).eval()
x = torch.rand(1, 3, 64, 64, device=device)
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 3433d1887..6c6acf627 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -693,12 +693,45 @@ class TestDeterminantToPolynomial(BaseTester):
poly = solver.determinant_to_polynomial(A)
assert poly.shape == (1, 11)
- @pytest.mark.parametrize("batch_size", [1, 2, 8])
+ @pytest.mark.parametrize("batch_size", [0, 1, 2, 8])
def test_shape(self, batch_size, device, dtype):
B: int = batch_size
A = torch.rand(B, 3, 13, device=device, dtype=dtype)
poly = solver.determinant_to_polynomial(A)
assert poly.shape == (B, 11)
+ assert poly.device == A.device
+ assert poly.dtype == A.dtype
+
+ def test_empty_batch_backward_6266(self, device, dtype):
+ """Empty coefficients retain their autograd connection to the input."""
+ A = torch.empty(0, 3, 13, device=device, dtype=dtype, requires_grad=True)
+ poly = solver.determinant_to_polynomial(A)
+ poly.sum().backward()
+ assert A.grad is not None
+ self.assert_close(A.grad, A.detach())
+
+ def test_non_contiguous_input(self, device, dtype):
+ A = torch.rand(2, 13, 3, device=device, dtype=dtype).mT
+ self.assert_close(solver.determinant_to_polynomial(A), solver.determinant_to_polynomial(A.contiguous()))
+
+ def test_gradcheck(self, device):
+ A = torch.rand(2, 3, 13, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(solver.determinant_to_polynomial, (A,), fast_mode=True)
+
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ def test_dynamo_fullgraph_6266(self, batch_size, device, dtype, torch_optimizer, optimizer_backend):
+ """Both batch sizes compile, and empty coefficients retain their autograd connection."""
+ if optimizer_backend == "jit":
+ pytest.skip("This regression exercises torch.compile(fullgraph=True).")
+ A = torch.rand(batch_size, 3, 13, device=device, dtype=dtype, requires_grad=batch_size == 0)
+ expected = solver.determinant_to_polynomial(A)
+ actual = torch_optimizer(solver.determinant_to_polynomial, fullgraph=True)(A)
+ assert actual.shape == (batch_size, 11)
+ self.assert_close(actual, expected)
+ if batch_size == 0:
+ actual.sum().backward()
+ assert A.grad is not None
+ self.assert_close(A.grad, A.detach())
@pytest.mark.parametrize(
"A_in, expected_poly_coeffs",
diff --git a/tests/losses/test_lovaz_hinge.py b/tests/losses/test_lovaz_hinge.py
index b5f337491..aa19d36dc 100644
--- a/tests/losses/test_lovaz_hinge.py
+++ b/tests/losses/test_lovaz_hinge.py
@@ -61,6 +61,19 @@ class TestLovaszHingeLoss(BaseTester):
with pytest.raises(ValueError, match="pred and target shapes must be the same"):
criterion(logits, labels)
+ @pytest.mark.parametrize("as_module", [False, True])
+ def test_empty_batch_6266(self, as_module, device, dtype):
+ """An empty batch flattens without a -1 to infer; the mean over no pixels is nan, as torch's mean is."""
+ logits = torch.rand(0, 1, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ labels = torch.randint(0, 2, (0, 4, 5), device=device)
+ loss_fn = kornia.losses.LovaszHingeLoss() if as_module else kornia.losses.lovasz_hinge_loss
+ loss = loss_fn(logits, labels)
+ assert loss.shape == ()
+ assert loss.dtype == dtype
+ assert torch.isnan(loss)
+ loss.backward()
+ assert logits.grad.shape == logits.shape
+
def test_smoke(self, device, dtype):
num_classes = 1
logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.py
index f8c7ea1d0..c2b36cc14 100644
--- a/tests/losses/test_lovaz_softmax.py
+++ b/tests/losses/test_lovaz_softmax.py
@@ -75,6 +75,19 @@ class TestLovaszSoftmaxLoss(BaseTester):
self.assert_close(criterion(logits, labels), expected, rtol=0, atol=0)
assert expected > criterion(logits, labels[:1])
+ @pytest.mark.parametrize("as_module", [False, True])
+ def test_empty_batch_6266(self, as_module, device, dtype):
+ """An empty batch flattens without a -1 to infer; the mean over no pixels is nan, as torch's mean is."""
+ logits = torch.rand(0, 3, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ labels = torch.randint(0, 3, (0, 4, 5), device=device)
+ loss_fn = kornia.losses.LovaszSoftmaxLoss() if as_module else kornia.losses.lovasz_softmax_loss
+ loss = loss_fn(logits, labels)
+ assert loss.shape == ()
+ assert loss.dtype == dtype
+ assert torch.isnan(loss)
+ loss.backward()
+ assert logits.grad.shape == logits.shape
+
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index c36d76488..90700be90 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -491,6 +491,40 @@ class TestMutualInformationValidation(BaseTester):
with pytest.raises((BaseError, ValueError), match="shape"):
module(signal)(other)
+ def test_signal_with_fewer_dims_reads_as_one_flat_signal(self, device, dtype, loss_fn, module, shape):
+ # The 2D and 3D losses flatten their last two or three dimensions; a 1-D signal is already flat.
+ signal = torch.linspace(0, 1, torch.Size(shape).numel(), device=device, dtype=dtype)
+ target = signal.flip(-1) ** 2
+ expected = loss_fn(signal.reshape(shape), target.reshape(shape))
+ self.assert_close(loss_fn(signal, target), expected, rtol=0, atol=0)
+ self.assert_close(module(target)(signal), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("batch", [(0,), (0, 3), (3, 0)])
+ def test_empty_batch(self, device, dtype, loss_fn, module, shape, batch):
+ # An empty batch gives one loss per (zero) leading index, like any other batch shape.
+ signal = torch.rand((*batch, *shape), device=device, dtype=dtype, requires_grad=True)
+ target = torch.rand((*batch, *shape), device=device, dtype=dtype)
+ mask = torch.ones(shape, device=device, dtype=torch.bool)
+ loss = loss_fn(signal, target)
+ assert loss.shape == batch
+ assert loss.dtype == dtype
+ masked_loss = loss_fn(signal, target, mask, mask)
+ assert masked_loss.shape == batch
+ assert module(target)(signal).shape == batch
+ assert module(target, mask)(signal, mask).shape == batch
+ loss.sum().backward()
+ assert signal.grad.shape == signal.shape
+ signal.grad = None
+ masked_loss.sum().backward()
+ assert signal.grad.shape == signal.shape
+
+ def test_empty_signal(self, device, dtype, loss_fn, module, shape):
+ signal = torch.rand((2, *shape[:-1], 0), device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="signals must have at least one sample"):
+ loss_fn(signal, signal)
+ with pytest.raises(BaseError, match="signals must have at least one sample"):
+ module(signal)
+
@pytest.mark.parametrize("kind", ["input_empty", "target_empty", "disjoint"])
def test_empty_mask_intersection(self, device, dtype, loss_fn, module, shape, kind):
signal = torch.arange(torch.Size(shape).numel(), device=device, dtype=dtype).reshape(shape)