Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): record list padding per box so writes cannot make it stale (#6595)

Dmytro Mishkin9578ff60e283
diff --git a/changelog.d/6595.breaking.md b/changelog.d/6595.breaking.md
new file mode 100644
index 000000000..b34cec067
--- /dev/null
+++ b/changelog.d/6595.breaking.md
@@ -0,0 +1 @@
+`torch.compile(..., fullgraph=True)` around the trimmed `to_tensor` export of a `Boxes` built from a list now raises `Unsupported` before torch 2.10, because that export reads its padding mask with `nonzero`. It used to compile, on the lengths recorded when the object was built. With `capture_dynamic_output_shape_ops` and `capture_scalar_outputs` both set it compiles, and on torch 2.5 and 2.6 it returns wrong rows with no error, from a miscompile of `nonzero` in torch. `as_padded_sequence=True` and default `torch.compile` return the right rows on those versions, and from torch 2.10 the call works. `boxes[0][None].to_tensor()` on boxes built from a list now returns the trimmed list `boxes[0:1]` returns; it used to return one tensor that kept the padding rows as `[0, 0, 1, 1]`.
diff --git a/changelog.d/6595.fixed.md b/changelog.d/6595.fixed.md
new file mode 100644
index 000000000..282b5e993
--- /dev/null
+++ b/changelog.d/6595.fixed.md
@@ -0,0 +1 @@
+`Boxes` built from a list now records its padding per box, so item assignment and `index_put` no longer make the trimmed `to_tensor` export drop real boxes or keep padding rows, and a `VideoBoxes` merged with list-built boxes exports and draws masks, with the padding as invalid zero rows. A selection such as `boxes[0]` now shares its validity with the original exactly as long as it shares its coordinates: after `to`, `type` or an in-place transform of either, filtering or writing through one no longer blanks rows of the other. A padding row written to a dense `Boxes` now exports as zeros and draws no mask; it used to export as `[0, 0, 1, 1]` and draw one pixel. `boxes[0, 1:2]`, a tuple of index tensors and a `(B, N)` boolean mask now read a list-built `Boxes`; they used to raise `IndexError`. A row written behind a padding row now stays in the trimmed export; it used to be dropped. A `VideoBoxes` with `T = 1` built from or merged with list boxes now exports one `(B, 1, N, ...)` tensor; it used to return a ragged list.
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index b8d1dd96e..fcfce07fb 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -173,12 +173,8 @@ class RandomMosaic(MixAugmentationBaseV2):
_offset[idx, 1] = batch_shapes_idx[:, -2] * j - src_box_idx[:, 0, 1]
_box = input.clone()
_idx = i * flags["mosaic_grid"][1] + j
+ # A list input pads each sample to the longest one; the tile keeps its source's padding.
_box[params["permutation"][:, 0]] = input[params["permutation"][:, _idx]]
- if input._N is not None:
- # A list input pads each sample to the longest one; the tile keeps its source's padding count.
- _box._N = list(input._N)
- for dst, src in params["permutation"][:, [0, _idx]].tolist():
- _box._N[dst] = input._N[src]
_box.translate(_offset, inplace=True)
if maybe_out_boxes is None:
maybe_out_boxes = _box
@@ -190,19 +186,17 @@ class RandomMosaic(MixAugmentationBaseV2):
if not bool(to_apply.all()):
# An unselected sample keeps its own boxes unchanged, followed by padding up to the mosaic box count.
- # The padding is recorded in ``_N`` and marked invalid, so every export gives all-zero rows for it, also
- # after a later geometric transform and in a container such as VideoBoxes that does not keep ``_N``.
+ # That padding is recorded and also marked invalid, so every export gives all-zero rows for it, also
+ # after a later geometric transform and in a container such as VideoBoxes that keeps no padding.
out_boxes._data[~to_apply, :num_boxes] = input._data[~to_apply]
out_boxes._valid[~to_apply, :num_boxes] = input._valid[~to_apply]
out_boxes._data[~to_apply, num_boxes:] = 0.0
out_boxes._valid[~to_apply, num_boxes:] = False
- padding = out_boxes._data.shape[1] - num_boxes
- merged_padding = out_boxes._N if out_boxes._N is not None else [0] * len(to_apply)
- input_padding = input._N if input._N is not None else [0] * len(to_apply)
- out_boxes._N = [
- merged if bool(selected) else own + padding
- for selected, merged, own in zip(to_apply, merged_padding, input_padding)
- ]
+ skipped = ~to_apply.cpu()
+ padding = out_boxes._padding_or_real()
+ padding[skipped, :num_boxes] = input._padding_or_real()[skipped]
+ padding[skipped, num_boxes:] = True
+ out_boxes._set_padding(padding)
return out_boxes
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index b32698b2a..91268fdf6 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -542,7 +542,7 @@ class _AugmentationBase(_BasicAugmentationBase):
blended_data = self._blend_by_prob(data_transformed, data_not_transformed, to_apply)
- # Reuse the not-transformed Boxes container (preserves mode/_N/is_batched/etc.)
+ # Reuse the not-transformed Boxes container (preserves mode/_padding/is_batched/etc.)
# and swap in the blended data, same effect as the index_put on .data.
output = output_not_transformed.clone()
output._data = blended_data
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index bff33adf4..6f8dfdfbd 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -25,7 +25,7 @@ from torch.distributions import Beta, Uniform
# Both moved to kornia.core.ops; re-exported so that existing imports from this module keep working.
from kornia.core.exceptions import InputRankError
from kornia.core.ops import _constant_tensor, _flatten_constant # noqa: F401
-from kornia.core.utils import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype, _to_device_nonblocking
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
@@ -63,7 +63,7 @@ def _pad_with_fill(
def _boxes_to_padded_tensor(boxes: Boxes, mode: str) -> torch.Tensor:
"""Export ``boxes`` as one dense tensor whose trailing padding rows are exactly zero.
- :class:`~kornia.geometry.boxes.Boxes` records per-sample trailing padding in ``_N`` and its default export
+ :class:`~kornia.geometry.boxes.Boxes` records which rows are list padding in ``_padding`` and its default export
returns a ragged list for such an object. The padding rows are zeroed after the export rather than stored as
zeros, because a zero stored box exports as ``[0, 0, 1, 1]`` in the exclusive ``'xyxy'``, ``'xywh'`` and
``'vertices'`` modes, which reads as a real one-pixel box.
@@ -71,13 +71,10 @@ def _boxes_to_padded_tensor(boxes: Boxes, mode: str) -> torch.Tensor:
out = boxes.to_tensor(mode, as_padded_sequence=True)
if not isinstance(out, torch.Tensor):
raise TypeError(f"Expected a padded tensor export. Got {type(out)}.")
- if boxes._N is None:
+ if boxes._padding is None or not boxes._is_batched:
return out
- num_boxes = out.shape[1]
- real = torch.tensor([num_boxes - n for n in boxes._N], device=out.device)
- valid = torch.arange(num_boxes, device=out.device)[None] < real[:, None]
- valid = valid.reshape(valid.shape + (1,) * (out.dim() - 2))
- return torch.where(valid, out, torch.zeros((), device=out.device, dtype=out.dtype))
+ padding = _to_device_nonblocking(boxes._padding, out.device)
+ return out.masked_fill(padding.reshape(padding.shape + (1,) * (out.dim() - 2)), 0.0)
def _frame_boxes(boxes: VideoBoxes) -> Boxes:
@@ -88,8 +85,9 @@ def _frame_boxes(boxes: VideoBoxes) -> Boxes:
videos with frame indices (#6173). The view shares the storage and the validity mask.
"""
frames = Boxes(boxes._data, False, mode=boxes._mode)
- frames._N = boxes._N
frames._valid = boxes._valid
+ if frames._data is not boxes._data: # the constructor cast integer coordinates, into a copy
+ frames._detach_masks()
frames._is_batched = boxes._is_batched
return frames
@@ -97,12 +95,13 @@ def _frame_boxes(boxes: VideoBoxes) -> Boxes:
def _video_boxes(frames: Boxes, temporal_channel_size: int) -> VideoBoxes:
"""Wrap frame-level :class:`Boxes` back into :class:`VideoBoxes` with ``temporal_channel_size`` frames.
- A ``VideoBoxes`` is a dense container, so the per-frame padding counts ``_N`` are not carried over. Padding a
- child adds, such as the rows a partial ``RandomMosaic`` gate pads a skipped frame with, is marked invalid
- instead; every export zeroes invalid rows and every indexed read or write carries them.
+ A ``VideoBoxes`` is a dense container and keeps no list padding. Padding a child adds, such as the rows a partial
+ ``RandomMosaic`` gate pads a skipped frame with, is marked invalid instead; every export zeroes invalid rows and
+ every indexed read or write carries them.
"""
boxes = VideoBoxes(frames._data, False, mode=frames._mode)
boxes._valid = frames._valid
+ boxes._set_padding(frames._padding)
boxes._is_batched = frames._is_batched
boxes.temporal_channel_size = temporal_channel_size
return boxes
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 14116203f..8ac0b5bc9 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -46,7 +46,7 @@ from torch import Size
from kornia.core._compat import _emit_deprecation_warning
from kornia.core.check import _check_async
from kornia.core.ops import eye_like
-from kornia.core.utils import is_compiling, is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_compiling, is_exporting
from kornia.geometry._coordinate import _cast_to_floating_point
from kornia.geometry.linalg import transform_points
@@ -72,6 +72,21 @@ def _merge_box_list(boxes: list[torch.Tensor], method: str = "pad") -> tuple[tor
return output, stats
+def _padding_mask(counts: list[int], num_boxes: int) -> torch.Tensor:
+ """Mark the last ``counts[i]`` of the ``num_boxes`` rows of each sample ``i`` in a ``(B, num_boxes)`` host mask."""
+ real = torch.as_tensor([num_boxes - n for n in counts], device="cpu", dtype=torch.long)
+ return torch.arange(num_boxes, device="cpu")[None] >= real[:, None]
+
+
+def _key_on_host(key: Any) -> Any:
+ """Move the tensors of an index key to the CPU, where the padding mask of a list-built :class:`Boxes` lives."""
+ if isinstance(key, torch.Tensor):
+ return key.cpu()
+ if isinstance(key, (tuple, list)):
+ return type(key)(_key_on_host(item) for item in key)
+ return key
+
+
def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor:
"""Transform 3D and 2D in kornia format by applying the transformation matrix M.
@@ -282,9 +297,16 @@ class Boxes:
or ``float64`` when that is the default dtype.
- A list of per-image tensors, ``(N_i, 4)`` or ``(N_i, 4, 2)`` in :meth:`from_tensor` and ``(N_i, 4, 2)``
in the constructor, is zero-padded to one ``(B, max N_i, 4, 2)`` batch; :meth:`to_tensor` then returns a
- list trimmed back to each image's boxes, or the padded tensor with ``as_padded_sequence=True``. Item
- assignment and :meth:`index_put` do not update the padding counts, so the trimmed export can then drop
- real boxes or keep padding (`#6283 <https://github.com/kornia/kornia/issues/6283>`_).
+ list trimmed back to each image's boxes, or the padded tensor with ``as_padded_sequence=True``.
+ - Which rows are padding is recorded per box and follows the coordinates through indexing, item assignment,
+ :meth:`index_put` and :meth:`merge`: a padding row written elsewhere stays padding, and a :class:`Boxes`
+ that does not come from a list writes real boxes. A raw tensor passed to :meth:`index_put` changes only
+ coordinates. Writing padding to a :class:`Boxes` that does not come from a list marks those rows invalid,
+ since that object has no trimmed export.
+ - A selection by integer or slice shares its coordinates, validity and padding with the object it came from,
+ as tensor indexing does, and any other key copies all three. :meth:`to` and :meth:`type` to another device or
+ dtype, and an in-place :meth:`transform_boxes`, :meth:`translate` or :meth:`merge`, end the sharing of all
+ three, for the object they are called on, whether it is the selection or the original.
- :meth:`filter_boxes_by_area` removes boxes without changing the shape: it zeroes their corners and marks
them invalid, and every export of an invalid box is exact zeros, after later transforms too.
- :meth:`transform_boxes`, :meth:`translate`, :meth:`clamp`, :meth:`filter_boxes_by_area`, :meth:`merge`
@@ -332,10 +354,10 @@ class Boxes:
raise_if_not_floating_point: bool = True,
mode: str = "vertices_plus",
) -> None:
- self._N: Optional[list[int]] = None
+ padding_counts: Optional[list[int]] = None
if isinstance(boxes, list):
- boxes, self._N = _merge_box_list(boxes)
+ boxes, padding_counts = _merge_box_list(boxes)
if not isinstance(boxes, torch.Tensor):
raise TypeError(f"Input boxes is not a Tensor. Got: {type(boxes)}.")
@@ -356,31 +378,86 @@ class Boxes:
self._data = boxes
self._mode = mode
- # Filtering can leave holes; _N only describes trailing list padding.
+ # ``_valid`` marks rows that stay in every export as exact zeros, such as the holes filtering leaves.
+ # ``_padding`` marks the rows a list input added, which the trimmed export drops and the padded export keeps as
+ # stored; it is ``None`` unless the object comes from a list. Every indexed read and write carries it with the
+ # coordinates, as it does ``_valid``, so it cannot go stale. It stays on the CPU, whatever the device of the
+ # boxes: the trimmed export needs its values to size the list it returns, and reading them there costs no
+ # device synchronization. Two objects share all of ``_data``, ``_valid`` and ``_padding`` or none of them, or a
+ # write through one would flag rows whose coordinates it cannot reach. Replacing the ``_data`` of an existing
+ # object therefore goes through ``_rebind_data``.
self._valid = torch.ones(boxes.shape[:-2], device=boxes.device, dtype=torch.bool)
+ self._padding: Optional[torch.Tensor] = None
+ if padding_counts is not None:
+ self._set_padding(_padding_mask(padding_counts, boxes.shape[1]))
def __setstate__(self, state: dict[str, Any]) -> None:
- self.__dict__.update(state)
+ self.__dict__.update({name: value for name, value in state.items() if name != "_N"})
if "_valid" not in state: # pickled before filtering kept validity: every box is valid
self._valid = torch.ones(self._data.shape[:-2], device=self._data.device, dtype=torch.bool)
+ if "_padding" not in state: # pickled when the padding was a list of trailing counts
+ self._padding = None
+ if state.get("_N") is not None:
+ self._set_padding(_padding_mask(state["_N"], self._data.shape[1]))
+ elif self._padding is not None: # ``torch.load(map_location=...)`` moves every tensor it finds
+ self._padding = self._padding.cpu()
+
+ def _set_padding(self, padding: Optional[torch.Tensor]) -> None:
+ """Record the host mask of the rows a list input added, or ``None`` for an object without any."""
+ self._padding = padding
+
+ def _detach_masks(self) -> None:
+ """Give ``_valid`` and ``_padding`` storage of their own, ``_valid`` on the device of the coordinates."""
+ self._valid = self._valid.to(device=self._data.device, copy=True)
+ if self._padding is not None:
+ self._padding = self._padding.clone()
+
+ def _rebind_data(self, data: torch.Tensor) -> None:
+ """Replace the coordinates of this object, and stop sharing its masks if ``data`` is another tensor.
+
+ Whatever shared the old coordinates, a selection or the object it came from, keeps them and the old masks.
+ """
+ if data is not self._data:
+ self._data = data
+ self._detach_masks()
+
+ def _valid_without_padding(self) -> torch.Tensor:
+ """Return ``_valid`` with the padding rows marked invalid, for a destination that has no trimmed export."""
+ if self._padding is None:
+ return self._valid
+ return self._valid & ~_to_device_nonblocking(self._padding, self._valid.device)
+
+ @property
+ def _N(self) -> Optional[list[int]]:
+ """Return the number of padding rows of each sample, or ``None`` for an object with no trimmed export."""
+ if self._padding is None or not self._is_batched:
+ return None
+ return self._padding.sum(dim=-1).tolist()
def __getitem__(self, key: slice | int | torch.Tensor) -> Boxes:
- data = self._data[key]
+ selected = self._data[key]
# an integer or 0-d integer tensor selects one box of unbatched boxes: keep the box axis
- one_box = data.ndim == 2 and not isinstance(key, tuple)
- new_box = type(self)(data.unsqueeze(0) if one_box else data, False)
+ one_box = selected.ndim == 2 and not isinstance(key, tuple)
+ if one_box:
+ selected = selected.unsqueeze(0)
+ new_box = type(self)(selected, False)
new_box._mode = self._mode
valid = self._valid[key]
new_box._valid = valid.unsqueeze(0) if one_box else valid
- # Select padding metadata with the same key as the box batch, including boolean masks.
- if self._N is not None:
- selected = torch.as_tensor(self._N, device=self._data.device)[key]
- new_box._N = None if selected.ndim == 0 else [int(n) for n in selected]
+ if self._padding is not None:
+ padding = self._padding[_key_on_host(key)]
+ new_box._padding = padding.unsqueeze(0) if one_box else padding
+ if new_box._data is not selected: # the constructor cast integer coordinates, into a copy
+ new_box._detach_masks()
return new_box
def __setitem__(self, key: slice | int | torch.Tensor, value: Boxes) -> Boxes:
self._data[key] = value._data
- self._valid[key] = value._valid
+ if self._padding is None:
+ self._valid[key] = value._valid_without_padding()
+ else:
+ self._valid[key] = value._valid
+ self._padding[_key_on_host(key)] = False if value._padding is None else value._padding
return self
@property
@@ -435,62 +512,40 @@ class Boxes:
Note:
When either input was created from a list, each batch row is repacked
- so that its real boxes precede all trailing padding. The merged object
- keeps the combined per-image padding counts in ``_N``.
+ so that its real boxes precede all of its padding, and the merged
+ object exports a list trimmed back to them.
"""
- padding: Optional[list[int]] = None
- if self._N is not None or boxes._N is not None:
- if self._data.shape[0] != boxes.data.shape[0]:
+ padding: Optional[torch.Tensor] = None
+ if self._padding is not None or boxes._padding is not None:
+ if (self._is_batched or boxes._is_batched) and self._data.shape[0] != boxes.data.shape[0]:
raise ValueError(
f"Batch size mismatch. Got {self._data.shape[0]} for self and {boxes.data.shape[0]} for boxes."
)
+ padding = torch.cat([operand._padding_or_real() for operand in (self, boxes)], dim=-1)
- self_padding = self._N if self._N is not None else [0] * self._data.shape[0]
- boxes_padding = boxes._N if boxes._N is not None else [0] * boxes.data.shape[0]
- data = torch.stack(
- [
- torch.cat(
- [
- self._data[i, : self._data.shape[-3] - self_pad],
- boxes.data[i, : boxes.data.shape[-3] - boxes_pad],
- self._data[i, self._data.shape[-3] - self_pad :],
- boxes.data[i, boxes.data.shape[-3] - boxes_pad :],
- ]
- )
- for i, (self_pad, boxes_pad) in enumerate(zip(self_padding, boxes_padding))
- ]
- )
- valid = torch.stack(
- [
- torch.cat(
- [
- self._valid[i, : self._valid.shape[-1] - self_pad],
- boxes._valid[i, : boxes._valid.shape[-1] - boxes_pad],
- self._valid[i, self._valid.shape[-1] - self_pad :],
- boxes._valid[i, boxes._valid.shape[-1] - boxes_pad :],
- ]
- )
- for i, (self_pad, boxes_pad) in enumerate(zip(self_padding, boxes_padding))
- ]
- )
- padding = [self_pad + boxes_pad for self_pad, boxes_pad in zip(self_padding, boxes_padding)]
- else:
- data = torch.cat([self._data, boxes.data], dim=-3)
- valid = torch.cat([self._valid, boxes._valid], dim=-1)
+ data = torch.cat([self._data, boxes.data], dim=-3)
+ valid = torch.cat([self._valid, boxes._valid], dim=-1)
- if inplace:
- self._data = data
- self._N = padding
- self._valid = valid
- return self
+ if padding is not None and self._is_batched:
+ order = padding.long().argsort(dim=-1, stable=True)
+ padding = padding.gather(-1, order)
+ order = _to_device_nonblocking(order, data.device)
+ data = data.take_along_dim(order[..., None, None], dim=-3)
+ valid = valid.gather(-1, order)
- obj = self.clone()
+ obj = self if inplace else self.clone()
obj._data = data
- obj._N = padding
obj._valid = valid
+ obj._set_padding(padding)
return obj
+ def _padding_or_real(self) -> torch.Tensor:
+ """Return the host padding mask, all ``False`` for an object that does not come from a list."""
+ if self._padding is not None:
+ return self._padding
+ return torch.zeros(self._valid.shape, device="cpu", dtype=torch.bool)
+
def index_put(
self,
indices: tuple[torch.Tensor, ...] | list[torch.Tensor],
@@ -510,8 +565,8 @@ class Boxes:
The indices address entries in the stored tensor, commonly
shaped ``(B, N, 4, 2)`` or ``(N, 4, 2)``.
values: Replacement coordinates. If a :class:`Boxes` object is
- passed, its coordinates and filtering validity are copied. Raw tensor writes
- change only coordinates and preserve the existing filtering validity.
+ passed, its coordinates, filtering validity and list padding are copied. Raw tensor writes
+ change only coordinates and preserve the existing filtering validity and list padding.
inplace: If ``True``, update this object and return ``self``. If
``False``, clone the current data first and return a new
:class:`Boxes` instance.
@@ -522,7 +577,11 @@ class Boxes:
obj = self if inplace else self.clone()
if isinstance(values, Boxes):
obj._data.index_put_(indices, values.data)
- obj._valid.index_put_(indices, values._valid)
+ if obj._padding is None:
+ obj._valid.index_put_(indices, values._valid_without_padding())
+ else:
+ obj._valid.index_put_(indices, values._valid)
+ obj._padding.index_put_(_key_on_host(indices), values._padding_or_real())
else:
obj._data.index_put_(indices, values)
return obj
@@ -817,6 +876,14 @@ class Boxes:
axis-aligned and still yields an export that differs from :attr:`data`, because the reduction
re-canonicalizes the vertex order.
+ .. warning::
+ Before torch 2.10, ``torch.compile(..., fullgraph=True)`` around the trimmed export of boxes built from a
+ list raises, because that export reads its rows with ``nonzero``, whose output size depends on the data.
+ Setting ``torch._dynamo.config.capture_dynamic_output_shape_ops``, as the error suggests, still raises.
+ Setting ``capture_scalar_outputs`` as well makes it compile, and on torch 2.5 and 2.6 it then returns wrong
+ rows with no error, from a miscompile of ``nonzero`` in torch. ``as_padded_sequence=True`` and default
+ ``torch.compile`` return the right rows on every one of these versions.
+
Args:
mode: the output box format, or ``None`` to reuse :attr:`mode`. That attribute depends on the
construction path: the constructor defaults to ``'vertices_plus'``, while :meth:`from_tensor`
@@ -831,8 +898,9 @@ class Boxes:
* 'vertices_plus': the inclusive stored vertex form.
as_padded_sequence: If this object was created from a list, return its padded tensor rather than a list
of tensors trimmed to their original lengths. The padded values follow the selected output mode.
- Batch slicing, index tensors, and boolean masks preserve the list metadata. Selecting a single
- batch element with an integer or scalar tensor returns an unbatched object without list metadata.
+ Batch slicing, index tensors, and boolean masks keep the list export. A selection that returns an
+ unbatched object, such as an integer or scalar tensor index, exports all its rows, padding included,
+ as one tensor.
Returns:
Boxes tensor in the ``mode`` format, or a list of tensors when the object was created from a list and
@@ -881,11 +949,12 @@ class Boxes:
valid = valid.reshape(valid.shape + (1,) * (boxes.ndim - valid.ndim))
boxes = boxes.masked_fill(~valid, 0.0)
- if self._N is not None and not as_padded_sequence:
- boxes = [torch.nn.functional.pad(o, (len(o.shape) - 1) * [0, 0] + [0, -n]) for o, n in zip(boxes, self._N)]
- else:
- boxes = boxes if self._is_batched else boxes.squeeze(0)
- return boxes
+ if self._padding is not None and self._is_batched and not as_padded_sequence:
+ keep = ~self._padding
+ samples, rows = keep.nonzero(as_tuple=True)
+ kept = boxes[_to_device_nonblocking(samples, boxes.device), _to_device_nonblocking(rows, boxes.device)]
+ return list(kept.split(keep.sum(dim=-1).tolist()))
+ return boxes if self._is_batched else boxes.squeeze(0)
def to_mask(self, height: int, width: int) -> torch.Tensor:
"""Convert 2D boxes to masks. Covered area is 1 and the remaining is 0.
@@ -944,10 +1013,9 @@ class Boxes:
clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))
clipped_boxes_xyxy[..., ::2].clamp_(0, width)
clipped_boxes_xyxy[..., 1::2].clamp_(0, height)
- if self._N is not None:
+ if self._padding is not None and is_batched:
# Padding is not a box, even when its coordinates have been changed by a transform.
- for i, n in enumerate(self._N):
- clipped_boxes_xyxy[i, clipped_boxes_xyxy.shape[1] - n :] = 0
+ clipped_boxes_xyxy.masked_fill_(_to_device_nonblocking(self._padding, device)[..., None], 0)
# -----------------
# CPU Hotpath (loop)
@@ -1014,7 +1082,7 @@ class Boxes:
transformed_boxes = _transform_boxes(self._data, M)
if inplace:
- self._data = transformed_boxes
+ self._rebind_data(transformed_boxes)
return self
obj = self.clone()
@@ -1102,8 +1170,7 @@ class Boxes:
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
raise ValueError("Boxes must be in floating point")
- self._data = self._data.to(device=device, dtype=dtype)
- self._valid = self._valid.to(device=self._data.device)
+ self._rebind_data(self._data.to(device=device, dtype=dtype))
return self
def clone(self) -> Boxes:
@@ -1111,12 +1178,12 @@ class Boxes:
Returns:
New :class:`Boxes` object with cloned tensor storage. Metadata such
- as the current mode, original list lengths, and batched flag is
+ as the current mode, list padding, and batched flag is
preserved.
"""
obj = type(self)(self._data.clone(), False)
obj._mode = self._mode
- obj._N = self._N
+ obj._padding = None if self._padding is None else self._padding.clone()
obj._valid = self._valid.clone()
obj._is_batched = self._is_batched
return obj
@@ -1130,8 +1197,7 @@ class Boxes:
Returns:
``self``, rebound to the converted tensor; the tensor it wrapped before is not modified.
"""
- self._data = self._data.type(dtype)
- self._valid = self._valid.to(device=self._data.device)
+ self._rebind_data(self._data.type(dtype))
return self
@@ -1168,6 +1234,9 @@ class VideoBoxes(Boxes):
- :meth:`Boxes.transform_boxes`, :meth:`Boxes.translate`, :meth:`Boxes.clamp`,
:meth:`Boxes.filter_boxes_by_area` and :meth:`Boxes.merge` return a new :class:`VideoBoxes`;
:meth:`Boxes.pad`, :meth:`Boxes.unpad`, :meth:`Boxes.to` and :meth:`Boxes.type` update and return ``self``.
+ - Every frame holds the same number of rows, with no trimmed export. The padding of list-built :class:`Boxes`
+ merged or written into a :class:`VideoBoxes` is marked invalid, so it exports as exact zeros in every mode
+ and draws no mask.
Attributes:
temporal_channel_size: Number of frames :math:`T` stored with the boxes.
@@ -1182,6 +1251,12 @@ class VideoBoxes(Boxes):
temporal_channel_size: int
+ def _set_padding(self, padding: Optional[torch.Tensor]) -> None:
+ """Mark the padding rows invalid: a video exports every row of every frame, with no trimmed export."""
+ self._padding = padding
+ self._valid = self._valid_without_padding()
+ self._padding = None
+
@classmethod
def from_tensor(cls, boxes: torch.Tensor | list[torch.Tensor], validate_boxes: bool = True) -> VideoBoxes:
r"""Create :class:`VideoBoxes` from a video box tensor.
@@ -1231,10 +1306,13 @@ class VideoBoxes(Boxes):
if selected.ndim == self._data.ndim:
selected = selected.unsqueeze(0)
- out = type(self)(selected.flatten(0, 1), False)
+ frames = selected.flatten(0, 1)
+ out = type(self)(frames, False)
out._mode = self._mode
selected_valid = self._valid.view(batch_size, self.temporal_channel_size, self._valid.shape[-1])[key]
out._valid = selected_valid.reshape(out._data.shape[:-2])
+ if out._data is not frames: # the constructor cast integer coordinates, into a copy
+ out._detach_masks()
out.temporal_channel_size = self.temporal_channel_size
return out
@@ -1252,7 +1330,8 @@ class VideoBoxes(Boxes):
# Explicit video counts: a clip with no boxes has 0 elements, so a -1 in the view would be ambiguous.
n, m = self._data.shape[0] // size, value.data.shape[0] // size
self._data.view(n, size, *self._data.shape[1:])[key] = value.data.view(m, size, *value.data.shape[1:])
- self._valid.view(n, size, self._valid.shape[-1])[key] = value._valid.view(m, size, value._valid.shape[-1])
+ value_valid = value._valid_without_padding()
+ self._valid.view(n, size, self._valid.shape[-1])[key] = value_valid.view(m, size, value_valid.shape[-1])
return self
def to_tensor(
@@ -1265,21 +1344,17 @@ class VideoBoxes(Boxes):
``None``, uses the stored mode (``vertices_plus`` by default).
as_padded_sequence: Forwarded to :meth:`Boxes.to_tensor`. It only
changes the result of a list-backed container; a
- :class:`VideoBoxes` built from a ``(B, T, N, 4, 2)`` tensor
- is not list-backed, so the value makes no difference there. The
- keyword is accepted because the inherited :meth:`Boxes.get_boxes_shape`
- and :meth:`Boxes.to_mask` pass it.
+ :class:`VideoBoxes` is never list-backed, so the value makes no
+ difference there. The keyword is accepted because the inherited
+ :meth:`Boxes.get_boxes_shape` and :meth:`Boxes.to_mask` pass it.
Returns:
Tensor shaped ``(B, T, ...)`` where :math:`T` is
``temporal_channel_size``.
"""
- out = super().to_tensor(mode, as_padded_sequence=as_padded_sequence)
+ out = cast(torch.Tensor, super().to_tensor(mode, as_padded_sequence=as_padded_sequence))
batch_size = self._data.shape[0] // self.temporal_channel_size
- if isinstance(out, torch.Tensor):
- return out.reshape(batch_size, self.temporal_channel_size, *out.shape[1:])
- # If returns a list of boxes.
- return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]
+ return out.reshape(batch_size, self.temporal_channel_size, *out.shape[1:])
def clone(self) -> VideoBoxes:
"""Create an independent copy of the video box container.
@@ -1290,7 +1365,6 @@ class VideoBoxes(Boxes):
"""
obj = type(self)(self._data.clone(), False)
obj._mode = self._mode
- obj._N = self._N
obj._valid = self._valid.clone()
obj._is_batched = self._is_batched
obj.temporal_channel_size = self.temporal_channel_size
diff --git a/tests/augmentation/test_host_sync.py b/tests/augmentation/test_host_sync.py
index 089287533..cf04f2691 100644
--- a/tests/augmentation/test_host_sync.py
+++ b/tests/augmentation/test_host_sync.py
@@ -235,6 +235,41 @@ class TestMaskWritesWithoutHostReads(BaseTester):
assert torch.equal(rain(x.cpu(), params=params), out.cpu())
[email protected](not torch.cuda.is_available(), reason="CUDA host synchronizations need a CUDA device")
+ "build",
+ [
+ pytest.param(lambda: K.RandomHorizontalFlip(p=1.0), id="flip"),
+ pytest.param(lambda: K.RandomAffine(15.0, p=0.5), id="affine_half"),
+ pytest.param(lambda: K.RandomMosaic(output_size=(16, 16), p=1.0), id="mosaic"),
+ pytest.param(lambda: K.RandomMosaic(output_size=(16, 16), p=0.5), id="mosaic_half"),
+ ],
+)
+def test_list_boxes_add_no_host_sync_to_dense_boxes(build) -> None:
+ # The padding mask of a list input lives on the host, so following it and trimming the export read nothing from the
+ # device: a list costs what a tensor costs, apart from validating each of its tensors on its own.
+ device = torch.device("cuda")
+ x = torch.rand(4, 3, 16, 16, device=device)
+ first = torch.tensor([[1.0, 1.0, 5.0, 5.0]], device=device)
+ second = torch.tensor([[2.0, 2.0, 6.0, 7.0], [3.0, 1.0, 8.0, 4.0]], device=device)
+ aug = K.AugmentationSequential(build(), data_keys=["input", "bbox_xyxy"])
+
+ def sites(boxes) -> dict[str, int]:
+ def call() -> None:
+ # Several draws, so that a gate of p=0.5 runs its skipped, selected and partial paths.
+ torch.manual_seed(0)
+ for _ in range(8):
+ aug(x, boxes)
+
+ call()
+ torch.cuda.synchronize()
+ counted = sync_sites(call)
+ del counted["geometry/boxes.py:_validate_box_values"]
+ return dict(counted)
+
+ assert sites([first, second, second[:0], first]) == sites(second[:1].expand(4, -1, -1))
+
+
@pytest.mark.skipif(not torch.cuda.is_available(), reason="host-to-device copies need a CUDA device")
def test_erasing_copies_box_parameters_not_masks(tmp_path) -> None:
# A large pageable copy stalls the host while the driver stages it, without any cudaStreamSynchronize: the
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index b277523f7..73d755098 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -18,11 +18,15 @@
import io
import pickle
import warnings
+from copy import copy as shallow_copy
+from copy import deepcopy
from functools import partial
+from operator import setitem
import pytest
import torch
+from kornia.core._compat import torch_version_lt
from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.geometry import boxes as boxes_module
from kornia.geometry.bbox import bbox_to_mask, bbox_to_mask3d, infer_bbox_shape, infer_bbox_shape3d
@@ -30,6 +34,145 @@ from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
+# Rows of the list-built boxes of the #6283 tests, in exclusive ``xyxy``; ``None`` marks a padding row. Sample 0 holds
+# one box and two padding rows, sample 1 three boxes. ``_NEW`` is the box the writes that do not copy a row bring in.
+_A = [1.0, 1.0, 3.0, 3.0]
+_B0 = [2.0, 2.0, 4.0, 5.0]
+_B1 = [3.0, 1.0, 6.0, 3.0]
+_B2 = [5.0, 4.0, 8.0, 7.0]
+_NEW = [0.0, 1.0, 2.0, 6.0]
+_SAMPLE_0 = [_A, None, None]
+_SAMPLE_1 = [_B0, _B1, _B2]
+
+# Each write takes the list-built boxes, the dense one-box ``(1, 4, 2)`` boxes of ``_NEW`` and a tensor factory on the
+# test device, and is listed with the rows it must leave.
+_PADDING_WRITES = {
+ # Whole samples.
+ "int": (lambda lb, new, t: setitem(lb, 0, lb[1]), [_SAMPLE_1, _SAMPLE_1]),
+ "int_writes_padding": (lambda lb, new, t: setitem(lb, 1, lb[0]), [_SAMPLE_0, _SAMPLE_0]),
+ "scalar_tensor": (lambda lb, new, t: setitem(lb, t(0), lb[t(1)]), [_SAMPLE_1, _SAMPLE_1]),
+ "slice": (lambda lb, new, t: setitem(lb, slice(0, 1), lb[1:2]), [_SAMPLE_1, _SAMPLE_1]),
+ "index_tensor": (lambda lb, new, t: setitem(lb, t([0]), lb[t([1])]), [_SAMPLE_1, _SAMPLE_1]),
+ "bool_batch": (lambda lb, new, t: setitem(lb, t([True, False]), lb[t([False, True])]), [_SAMPLE_1, _SAMPLE_1]),
+ # Single rows, by a boolean mask over (B, N) and by tuple keys. A row written behind a padding row leaves a hole.
+ "bool_rows": (
+ lambda lb, new, t: setitem(lb, t([[False, True, False], [False] * 3]), new),
+ [[_A, _NEW, None], _SAMPLE_1],
+ ),
+ "bool_rows_hole": (
+ lambda lb, new, t: setitem(lb, t([[False, False, True], [False] * 3]), new),
+ [[_A, None, _NEW], _SAMPLE_1],
+ ),
+ "bool_rows_write_padding": (
+ lambda lb, new, t: setitem(
+ lb, t([[False] * 3, [False, True, False]]), lb[t([[False, True, False], [False] * 3])]
+ ),
+ [_SAMPLE_0, [_B0, None, _B2]],
+ ),
+ "tuple_int_slice": (lambda lb, new, t: setitem(lb, (0, slice(1, 2)), new), [[_A, _NEW, None], _SAMPLE_1]),
+ "tuple_tensors": (lambda lb, new, t: setitem(lb, (t([0]), t([2])), new), [[_A, None, _NEW], _SAMPLE_1]),
+ "tuple_slices": (
+ lambda lb, new, t: setitem(lb, (slice(None), slice(2, 3)), new),
+ [[_A, None, _NEW], [_B0, _B1, _NEW]],
+ ),
+ "tuple_read": (
+ lambda lb, new, t: setitem(lb, (1, slice(0, 1)), lb[(0, slice(1, 2))]),
+ [_SAMPLE_0, [None, _B1, _B2]],
+ ),
+ # Through and from the unbatched object of one sample, which shares the storage of its coordinates and masks.
+ "unbatched_view": (lambda lb, new, t: setitem(lb[0], slice(1, 2), new), [[_A, _NEW, None], _SAMPLE_1]),
+ "unbatched_value": (lambda lb, new, t: setitem(lb, (1, slice(1, 2)), lb[0][1:2]), [_SAMPLE_0, [_B0, None, _B2]]),
+ # A singleton broadcasts over the rows it is written to.
+ "singleton": (lambda lb, new, t: setitem(lb, 0, new), [[_NEW, _NEW, _NEW], _SAMPLE_1]),
+ "singleton_padding": (lambda lb, new, t: setitem(lb, 1, lb[0][1:2]), [_SAMPLE_0, [None, None, None]]),
+ "singleton_batched": (lambda lb, new, t: setitem(lb, 0, lb[1:2][:, 2:3]), [[_B2, _B2, _B2], _SAMPLE_1]),
+ # index_put, with the same keys.
+ "index_put_sample": (
+ lambda lb, new, t: lb.index_put((t([0]),), lb[1:2].clone(), inplace=True),
+ [_SAMPLE_1, _SAMPLE_1],
+ ),
+ "index_put_writes_padding": (
+ lambda lb, new, t: lb.index_put((t([1]),), lb[0:1].clone(), inplace=True),
+ [_SAMPLE_0, _SAMPLE_0],
+ ),
+ "index_put_row": (
+ lambda lb, new, t: lb.index_put((t([0]), t([1])), new, inplace=True),
+ [[_A, _NEW, None], _SAMPLE_1],
+ ),
+ "index_put_list": (
+ lambda lb, new, t: lb.index_put([t([0]), t([2])], new, inplace=True),
+ [[_A, None, _NEW], _SAMPLE_1],
+ ),
+ "index_put_row_padding": (
+ lambda lb, new, t: lb.index_put((t([1]), t([1])), lb[0][1:2].clone(), inplace=True),
+ [_SAMPLE_0, [_B0, None, _B2]],
+ ),
+}
+
+
+def _other_dtype(dtype: torch.dtype) -> torch.dtype:
+ # Not float64, which MPS cannot allocate.
+ return torch.float16 if dtype == torch.float32 else torch.float32
+
+
+def _batch_rows(boxes: Boxes) -> int:
+ return boxes.data.shape[0] if boxes.data.ndim == 4 else 1
+
+
+def _identity(boxes: Boxes) -> torch.Tensor:
+ return torch.eye(3, device=boxes.device, dtype=boxes.dtype).repeat(_batch_rows(boxes), 1, 1)
+
+
+def _one_box_per_sample(boxes: Boxes) -> Boxes:
+ corners = torch.zeros(boxes.data.shape[:-3] + (1, 4, 2), device=boxes.device, dtype=boxes.dtype)
+ return Boxes(corners, False)
+
+
+def _bounds(boxes: Boxes, value: float, width: int = 2) -> torch.Tensor:
+ return torch.full((_batch_rows(boxes), width), value, device=boxes.device, dtype=boxes.dtype)
+
+
+# Every public method that changes the object it is called on, as ``name: (method, call)``. Those that move the
+# coordinates to other storage must take the masks along. The test below fails until a new public method is listed here
+# or in ``_LEAVES_THE_OBJECT_ALONE``, so that it is checked on a view before anything relies on it.
+_IN_PLACE_OPERATIONS = {
+ "to_dtype": ("to", lambda b: b.to(dtype=_other_dtype(b.dtype))),
+ "to_same": ("to", lambda b: b.to(dtype=b.dtype)),
+ "to_cpu": ("to", lambda b: b.to(device=torch.device("cpu"))),
+ "type_dtype": ("type", lambda b: b.type(_other_dtype(b.dtype))),
+ "type_same": ("type", lambda b: b.type(b.dtype)),
+ "transform_boxes": ("transform_boxes", lambda b: b.transform_boxes(_identity(b), inplace=True)),
+ "transform_boxes_": ("transform_boxes_", lambda b: b.transform_boxes_(_identity(b))),
+ "translate": ("translate", lambda b: b.translate(_bounds(b, 0.0), inplace=True)),
+ "clamp": ("clamp", lambda b: b.clamp(_bounds(b, -1.0), _bounds(b, 100.0), inplace=True)),
+ "pad": ("pad", lambda b: b.pad(_bounds(b, 0.0, 4))),
+ "unpad": ("unpad", lambda b: b.unpad(_bounds(b, 0.0, 4))),
+ "filter_boxes_by_area": ("filter_boxes_by_area", lambda b: b.filter_boxes_by_area(min_area=0.0, inplace=True)),
+ "merge": ("merge", lambda b: b.merge(_one_box_per_sample(b), inplace=True)),
+ "index_put": (
+ "index_put",
+ lambda b: b.index_put((torch.tensor([0], device=b.device),), b.data[:1] + 0.0, inplace=True),
+ ),
+}
+_LEAVES_THE_OBJECT_ALONE = {
+ "clone",
+ "compute_area",
+ "data",
+ "device",
+ "dtype",
+ "from_tensor",
+ "get_boxes_shape",
+ "mode",
+ "shape",
+ "to_mask",
+ "to_tensor",
+ "trim",
+}
+
+
+def _same_storage(first: torch.Tensor, second: torch.Tensor) -> bool:
+ return first.untyped_storage()._cdata == second.untyped_storage()._cdata
+
def _legacy_onnx_to_mask_pairs(
model: torch.nn.Module, vertices: list[torch.Tensor]
@@ -560,6 +703,395 @@ class TestBoxes2D(BaseTester):
assert scalar._N is None
assert isinstance(scalar.to_tensor("xyxy"), torch.Tensor)
+ @staticmethod
+ def _padding_boxes(device, dtype):
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ second = torch.tensor(_SAMPLE_1, device=device, dtype=dtype)
+ return Boxes.from_tensor([first, second], mode="xyxy")
+
+ def _assert_padding_rows(self, boxes, rows, device, dtype, height=10, width=10):
+ # The default export holds exactly the rows that are not padding, in order, and only those draw a mask.
+ exported = boxes.to_tensor("xyxy")
+ assert isinstance(exported, list)
+ assert len(exported) == len(rows)
+ assert boxes._N == [sum(row is None for row in sample) for sample in rows]
+ masks = boxes.to_mask(height, width)
+ assert masks.shape == (len(rows), len(rows[0]), height, width)
+ for out, sample, sample_masks in zip(exported, rows, masks):
+ real = [row for row in sample if row is not None]
+ self.assert_close(out, torch.tensor(real, device=device, dtype=dtype).reshape(-1, 4), atol=0.0, rtol=0.0)
+ for row, row_mask in zip(sample, sample_masks):
+ expected = torch.zeros(height, width, device=device, dtype=dtype)
+ if row is not None:
+ expected[int(row[1]) : int(row[3]), int(row[0]) : int(row[2])] = 1.0
+ self.assert_close(row_mask, expected, atol=0.0, rtol=0.0)
+ for mode in ("xyxy_plus", "xywh", "vertices", "vertices_plus"):
+ lengths = [len(out) for out in boxes.to_tensor(mode)]
+ assert lengths == [sum(row is not None for row in sample) for sample in rows], mode
+
+ def test_list_padding_reported_cases_6283(self, device, dtype):
+ b = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)
+ lb = Boxes([b, torch.cat([b + 2, b + 4, b + 6])])
+ lb[0] = lb[1]
+ assert [len(t) for t in lb.to_tensor("xyxy")] == [3, 3]
+
+ lb = Boxes([b, torch.cat([b + 2, b + 4, b + 6])])
+ out = lb.index_put((torch.tensor([0], device=device),), lb[1:2])
+ assert [len(t) for t in out.to_tensor("xyxy")] == [3, 3]
+ assert [len(t) for t in lb.to_tensor("xyxy")] == [1, 3]
+
+ a = b[0]
+ v = VideoBoxes.from_tensor(a.reshape(1, 1, 1, 4, 2).repeat(2, 2, 1, 1, 1))
+ v = v.merge(Boxes([a[None], torch.stack([a, a + 2]), a[None], a[None]]))
+ assert v.to_tensor().shape == (2, 2, 2 + 1, 4, 2)
+ assert v.to_mask(8, 8).shape == (2, 2, 2 + 1, 8, 8)
+
+ @pytest.mark.parametrize("write", _PADDING_WRITES.keys())
+ def test_list_padding_follows_every_write_6283(self, write, device, dtype):
+ # The padding follows each indexed write with the coordinates, so the trimmed export neither cuts a real box
+ # nor keeps a padding row, and the padded export and the masks agree with it.
+ writer, rows = _PADDING_WRITES[write]
+ boxes = self._padding_boxes(device, dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ writer(boxes, new, lambda value: torch.tensor(value, device=device))
+ self._assert_padding_rows(boxes, rows, device, dtype)
+ assert boxes.to_tensor("xyxy", as_padded_sequence=True).shape == (2, 3, 4)
+
+ @pytest.mark.parametrize("write", ["int", "bool_rows_hole", "unbatched_view", "index_put_row_padding"])
+ def test_list_padding_after_a_write_survives_copies_6283(self, write, device, dtype):
+ writer, rows = _PADDING_WRITES[write]
+ boxes = self._padding_boxes(device, dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ writer(boxes, new, lambda value: torch.tensor(value, device=device))
+ identity = torch.eye(3, device=device, dtype=dtype).expand(2, -1, -1)
+ low, high = torch.zeros(2, 2, device=device, dtype=dtype), torch.full((2, 2), 9.0, device=device, dtype=dtype)
+ buffer = io.BytesIO()
+ torch.save(boxes, buffer)
+ buffer.seek(0)
+ for copied in (
+ boxes.clone(),
+ shallow_copy(boxes),
+ deepcopy(boxes),
+ pickle.loads(pickle.dumps(boxes)), # noqa: S301
+ torch.load(buffer, map_location=device, weights_only=False),
+ boxes.clone().to(device=device),
+ boxes.clone().type(dtype),
+ boxes.transform_boxes(identity),
+ boxes.clamp(low, high),
+ boxes.filter_boxes_by_area(min_area=0.0),
+ boxes[0:2],
+ boxes[torch.tensor([True, True], device=device)],
+ ):
+ self._assert_padding_rows(copied, rows, device, dtype)
+
+ def test_list_padding_copies_are_independent_6283(self, device, dtype):
+ boxes = self._padding_boxes(device, dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ cloned = boxes.clone()
+ cloned[0, 1:2] = new
+ self._assert_padding_rows(cloned, [[_A, _NEW, None], _SAMPLE_1], device, dtype)
+ self._assert_padding_rows(boxes, [_SAMPLE_0, _SAMPLE_1], device, dtype)
+ written = boxes.index_put((torch.tensor([0], device=device), torch.tensor([2], device=device)), new)
+ self._assert_padding_rows(written, [[_A, None, _NEW], _SAMPLE_1], device, dtype)
+ self._assert_padding_rows(boxes, [_SAMPLE_0, _SAMPLE_1], device, dtype)
+
+ def test_list_padding_follows_a_move_to_the_device_6283(self, device, dtype):
+ # The object is built elsewhere and moved, so its keys and its tensors are on the device of the test.
+ boxes = self._padding_boxes(torch.device("cpu"), dtype).to(device=device)
+ self._assert_padding_rows(boxes, [_SAMPLE_0, _SAMPLE_1], device, dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ boxes[torch.tensor([0], device=device), torch.tensor([1], device=device)] = new
+ self._assert_padding_rows(boxes, [[_A, _NEW, None], _SAMPLE_1], device, dtype)
+ selected = boxes[torch.tensor([True, False], device=device)]
+ self._assert_padding_rows(selected, [[_A, _NEW, None]], device, dtype)
+
+ def test_list_padding_write_then_merge_6283(self, device, dtype):
+ # The merge moves every padding row behind the real rows of both operands, holes included.
+ boxes = self._padding_boxes(device, dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ boxes[0, 2:3] = new
+ extra = Boxes.from_tensor(torch.tensor([[_B0], [_B1]], device=device, dtype=dtype), mode="xyxy")
+ merged = boxes.merge(extra)
+ self._assert_padding_rows(merged, [[_A, _NEW, _B0, None], [_B0, _B1, _B2, _B1]], device, dtype)
+ reverse = extra.merge(boxes)
+ self._assert_padding_rows(reverse, [[_B0, _A, _NEW, None], [_B1, _B0, _B1, _B2]], device, dtype)
+ both = boxes.merge(self._padding_boxes(device, dtype))
+ self._assert_padding_rows(both, [[_A, _NEW, _A, None, None, None], [*_SAMPLE_1, *_SAMPLE_1]], device, dtype)
+ boxes.merge(extra, inplace=True)
+ self._assert_padding_rows(boxes, [[_A, _NEW, _B0, None], [_B0, _B1, _B2, _B1]], device, dtype)
+
+ def test_list_padding_merge_of_unbatched_selections_6283(self, device, dtype):
+ # Each operand exports all of its rows, as the batched object's padded export does, and the merge keeps their
+ # order: an unbatched object has no ragged export to trim for. The merged rows remember which were padding.
+ boxes = self._padding_boxes(device, dtype)
+ padded = boxes.to_tensor("xyxy", as_padded_sequence=True)
+ merged = boxes[0].merge(boxes[1])
+ self.assert_close(merged.to_tensor("xyxy"), padded.flatten(0, 1), atol=0.0, rtol=0.0)
+ assert merged.data.shape == (6, 4, 2)
+ restored = self._padding_boxes(device, dtype)
+ restored[1] = merged[0:3]
+ self._assert_padding_rows(restored, [_SAMPLE_0, _SAMPLE_0], device, dtype)
+
+ def test_rebatched_selection_of_list_boxes_is_the_slice_6283(self, device, dtype):
+ boxes = self._padding_boxes(device, dtype)
+ rebatched = boxes[0][None].to_tensor("xyxy")
+ assert isinstance(rebatched, list)
+ self.assert_close(rebatched[0], boxes[0:1].to_tensor("xyxy")[0], atol=0.0, rtol=0.0)
+
+ def test_convention_list_padding_is_not_filter_validity_6283(self, device, dtype):
+ # The two record different things and export differently. A filtered row stays where it is as a zero row. A
+ # padding row is trimmed from the default export and stays a stored row in the padded one, so ``_valid`` alone
+ # could not express it.
+ boxes = self._padding_boxes(device, dtype).filter_boxes_by_area(max_area=3.0)
+ exported = boxes.to_tensor("xyxy")
+ zero = [0.0, 0.0, 0.0, 0.0]
+ stored_zero = [0.0, 0.0, 1.0, 1.0]
+ self.assert_close(exported[0], torch.tensor([_A], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(exported[1], torch.tensor([_B0, _B1, zero], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ padded = torch.tensor([[_A, stored_zero, stored_zero], [_B0, _B1, zero]], device=device, dtype=dtype)
+ self.assert_close(boxes.to_tensor("xyxy", as_padded_sequence=True), padded, atol=0.0, rtol=0.0)
+ masks = boxes.to_mask(10, 10)
+ assert masks[0, 1:].count_nonzero() == 0
+ assert masks[1, 2].count_nonzero() == 0
+
+ def test_convention_index_put_raw_tensor_keeps_the_padding_6283(self, device, dtype):
+ # A raw tensor brings coordinates and nothing else: padding stays padding, as a filtered row stays filtered, so
+ # shifting a whole sample moves its padding rows without turning them into boxes.
+ boxes = self._padding_boxes(device, dtype)
+ shifted = boxes.index_put((torch.tensor([0], device=device),), boxes.data[:1] + 1.0)
+ exported = shifted.to_tensor("xyxy")
+ self.assert_close(exported[0], torch.tensor([_A], device=device, dtype=dtype) + 1.0, atol=0.0, rtol=0.0)
+ assert [len(out) for out in exported] == [1, 3]
+
+ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])
+ @pytest.mark.parametrize("index_put", [False, True])
+ def test_convention_padding_written_to_dense_boxes_is_invalid_6283(self, index_put, mode, device, dtype):
+ # A dense container has no trimmed export, so a padding row written to it is not a box: it exports as an exact
+ # zero row instead of the stored zero corners' one-pixel box, and it draws no mask.
+ list_boxes = self._padding_boxes(device, dtype)
+ dense = Boxes.from_tensor(torch.tensor([_SAMPLE_1, _SAMPLE_1], device=device, dtype=dtype), mode="xyxy")
+ real = dense.to_tensor(mode)
+ if index_put:
+ dense.index_put((torch.tensor([0], device=device),), list_boxes[0:1], inplace=True)
+ else:
+ dense[0] = list_boxes[0]
+ assert dense._N is None
+ exported = dense.to_tensor(mode)
+ assert isinstance(exported, torch.Tensor)
+ assert exported[0, 1:].count_nonzero() == 0
+ self.assert_close(exported[1], real[1], atol=0.0, rtol=0.0)
+ first = Boxes.from_tensor(torch.tensor([_A], device=device, dtype=dtype), mode="xyxy").to_tensor(mode)
+ self.assert_close(exported[0, :1], first, atol=0.0, rtol=0.0)
+ masks = dense.to_mask(10, 10)
+ assert masks[0, 0].count_nonzero() > 0
+ assert masks[0, 1:].count_nonzero() == 0
+
+ def test_unpickle_with_padding_counts_6283(self, device, dtype):
+ # A Boxes pickled by an earlier kornia records its padding as trailing counts, and loads as the same padding.
+ boxes = self._padding_boxes(device, dtype)
+ boxes.__dict__.pop("_padding", None)
+ boxes.__dict__["_N"] = [2, 0]
+ restored = pickle.loads(pickle.dumps(boxes)) # noqa: S301
+ self._assert_padding_rows(restored, [_SAMPLE_0, _SAMPLE_1], device, dtype)
+ restored[0] = restored[1]
+ self._assert_padding_rows(restored, [_SAMPLE_1, _SAMPLE_1], device, dtype)
+
+ def test_list_export_gradcheck_follows_the_written_rows_6283(self, device):
+ def export(first, second, written):
+ boxes = Boxes([first, second])
+ boxes[0, 1:2] = Boxes(written)
+ assert [len(rows) for rows in boxes.to_tensor("xyxy")] == [2, 2]
+ return tuple(boxes.to_tensor("xyxy"))
+
+ corners = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]]], device=device, dtype=torch.float64)
+ first = corners.clone().requires_grad_()
+ second = torch.cat([corners + 1.0, corners + 2.0]).requires_grad_()
+ written = (corners + 3.0).requires_grad_()
+ self.gradcheck(export, (first, second, written))
+
+ def test_padded_helper_zeroes_list_padding_6283(self, device, dtype):
+ from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
+
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ second = torch.tensor([_B0, _B1], device=device, dtype=dtype)
+ exported = _boxes_to_padded_tensor(Boxes.from_tensor([first, second], mode="xyxy"), "xyxy")
+ assert exported.shape == (2, 2, 4)
+ assert (exported[0, 1] == 0).all()
+ self.assert_close(exported[1], second)
+
+ def test_tuple_key_of_device_tensors_on_list_boxes_6283(self, device, dtype):
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ second = torch.tensor([_B0, _B1], device=device, dtype=dtype)
+ boxes = Boxes.from_tensor([first, second], mode="xyxy")
+ selected = boxes[(torch.tensor([1], device=device), torch.tensor([1], device=device))]
+ self.assert_close(selected.to_tensor("xyxy", as_padded_sequence=True), second[1:])
+
+ def test_loaded_list_boxes_keep_their_padding_on_the_cpu_6283(self, device, dtype):
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ second = torch.tensor([_B0, _B1], device=device, dtype=dtype)
+ buffer = io.BytesIO()
+ torch.save(Boxes.from_tensor([first, second], mode="xyxy"), buffer)
+ buffer.seek(0)
+ loaded = torch.load(buffer, map_location=device, weights_only=False)
+ assert loaded._padding.device.type == "cpu"
+ assert loaded._N == [1, 0]
+
+ def test_scalar_selection_of_a_list_view_keeps_its_padding_6283(self, device, dtype):
+ # A scalar selection of an unbatched object keeps a box axis (#6478). The padding mask takes that axis as
+ # ``_valid`` does and stays shared, so a write through the selection marks the row of the parent as real.
+ for key in (1, -2, torch.tensor(1, device=device)):
+ boxes = self._padding_boxes(device, dtype)
+ selected = boxes[0][key]
+ assert selected.shape == (1, 4, 2)
+ assert selected._padding.shape == selected._valid.shape == (1,)
+ assert _same_storage(selected.data, boxes.data)
+ assert _same_storage(selected._valid, boxes._valid)
+ assert _same_storage(selected._padding, boxes._padding)
+ selected[0] = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ self._assert_padding_rows(boxes, [[_A, _NEW, None], _SAMPLE_1], device, dtype)
+
+ def test_view_sweep_lists_every_public_method_6283(self):
+ listed = {method for method, _ in _IN_PLACE_OPERATIONS.values()} | _LEAVES_THE_OBJECT_ALONE
+ assert {name for name in dir(Boxes) if not name.startswith("_")} == listed
+
+ @pytest.mark.parametrize("selection", ["int", "slice"])
+ @pytest.mark.parametrize("target", ["view", "parent"])
+ @pytest.mark.parametrize("operation", _IN_PLACE_OPERATIONS.keys())
+ def test_view_shares_coordinates_and_masks_together_6283(self, operation, target, selection, device, dtype):
+ # A selection shares its coordinates, its validity and its padding with its parent, all three or none. Rows
+ # flagged through a mask whose coordinates another object holds would come apart from them on the next write.
+ boxes = self._padding_boxes(device, dtype)
+ view, row = (boxes[0], slice(1, 2)) if selection == "int" else (boxes[0:1], (0, slice(1, 2)))
+ _IN_PLACE_OPERATIONS[operation][1](view if target == "view" else boxes)
+
+ shared = _same_storage(view.data, boxes.data)
+ assert _same_storage(view._valid, boxes._valid) == shared
+ assert _same_storage(view._padding, boxes._padding) == shared
+
+ def state(box):
+ return box.data.clone(), box._valid.clone(), box._padding.clone()
+
+ def written(box):
+ value = Boxes.from_tensor(torch.tensor([_NEW], device=box.device, dtype=box.dtype), mode="xyxy")
+ filtered = value.clone()
+ filtered._valid[:] = False
+ return value, filtered
+
+ # A write through the view reaches the parent wholly or not at all, and the other way around.
+ parent_before = state(boxes)
+ value, filtered = written(view)
+ view[row] = value
+ view[row] = filtered
+ data, valid, padding = state(boxes)
+ if shared:
+ assert not padding[0, 1]
+ assert not valid[0, 1]
+ self.assert_close(data[0, 1], value.data[0].to(data.dtype), atol=0.0, rtol=0.0)
+ else:
+ for after, before in zip((data, valid, padding), parent_before):
+ assert torch.equal(after, before)
+
+ view_before = state(view)
+ value, filtered = written(boxes)
+ boxes[0, 2:3] = value
+ boxes[0, 2:3] = filtered
+ data, valid, padding = state(view)
+ data, valid, padding = (data, valid, padding) if selection == "int" else (data[0], valid[0], padding[0])
+ if shared:
+ assert not padding[2]
+ assert not valid[2]
+ self.assert_close(data[2], value.data[0].to(data.dtype), atol=0.0, rtol=0.0)
+ else:
+ for after, before in zip(state(view), view_before):
+ assert torch.equal(after, before)
+
+ def test_view_rebound_to_another_dtype_keeps_its_parents_rows_6283(self, device, dtype):
+ boxes = self._padding_boxes(device, dtype)
+ sample = boxes[0].to(dtype=_other_dtype(dtype))
+ sample[1:2] = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ self._assert_padding_rows(boxes, [_SAMPLE_0, _SAMPLE_1], device, dtype)
+ written = sample.to_tensor("xyxy", as_padded_sequence=True)
+ self.assert_close(written[1], torch.tensor(_NEW, device=device, dtype=written.dtype), atol=0.0, rtol=0.0)
+
+ def test_view_of_a_rebound_parent_keeps_its_rows_6283(self, device, dtype):
+ boxes = self._padding_boxes(device, dtype)
+ sample = boxes[0]
+ boxes.to(dtype=_other_dtype(dtype))
+ sample[1:2] = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy")
+ assert boxes._N == [2, 0]
+ assert boxes.data[0, 1].count_nonzero() == 0
+
+ def test_selection_the_constructor_casts_shares_nothing_6283(self, device, dtype):
+ # ``type`` accepts an integer dtype, and the constructor casts a selection of it to floating point, so the
+ # selection holds a copy of the coordinates and must not share the masks.
+ boxes = self._padding_boxes(device, dtype).type(torch.long)
+ selected = boxes[0]
+ assert selected.data.is_floating_point()
+ assert not _same_storage(selected.data, boxes.data)
+ assert not _same_storage(selected._valid, boxes._valid)
+ assert not _same_storage(selected._padding, boxes._padding)
+ selected[1:2] = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=selected.dtype), mode="xyxy")
+ assert boxes._N == [2, 0]
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("export", ["trimmed", "padded", "to_mask"])
+ def test_dynamo_list_padding_of_a_preconstructed_object_6283(self, export, device, dtype, torch_optimizer):
+ # The object is built outside the graph, so its mask is an input of it. One compiled function follows objects
+ # whose padding differs, an object that was written to included.
+ if export == "trimmed" and torch_version_lt(2, 10, 0):
+ pytest.skip(
+ "fullgraph raises Unsupported at nonzero on torch 2.5.1 to 2.9.1 (measured); it passes from 2.10.0"
+ )
+ functions = {
+ "trimmed": lambda boxes: boxes.to_tensor("xyxy"),
+ "padded": lambda boxes: boxes.to_tensor("xyxy", as_padded_sequence=True),
+ "to_mask": lambda boxes: boxes.to_mask(10, 10),
+ }
+ function = functions[export]
+ compiled = torch_optimizer(function, fullgraph=True)
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ three = torch.tensor(_SAMPLE_1, device=device, dtype=dtype)
+ other = Boxes.from_tensor([three, three[:2]], mode="xyxy")
+ written = self._padding_boxes(device, dtype)
+ written[0] = written[1]
+ for boxes in (Boxes.from_tensor([first, three], mode="xyxy"), other, written):
+ actual, expected = compiled(boxes), function(boxes)
+ pairs = list(zip(actual, expected)) if isinstance(expected, list) else [(actual, expected)]
+ assert len(pairs) == (len(expected) if isinstance(expected, list) else 1)
+ for out, want in pairs:
+ self.assert_close(out, want, atol=0.0, rtol=0.0)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.skipif(
+ torch_version_lt(2, 10, 0),
+ reason="fullgraph raises Unsupported at nonzero for any list-built object on torch 2.5.1 to 2.9.1 (measured); "
+ "it passes from 2.10.0",
+ )
+ def test_dynamo_list_padding_is_fullgraph_6283(self, device, dtype, torch_optimizer):
+ # Writes, merges and both exports stay in one graph, for a written object as for one nothing touched.
+ first = torch.tensor([_A], device=device, dtype=dtype)
+ second = torch.tensor(_SAMPLE_1, device=device, dtype=dtype)
+ new = Boxes.from_tensor(torch.tensor([_NEW], device=device, dtype=dtype), mode="xyxy").data
+
+ def untouched(x, y):
+ boxes = Boxes.from_tensor([x, y], mode="xyxy", validate_boxes=False)
+ return boxes.to_tensor("xyxy"), boxes.to_tensor("xyxy", as_padded_sequence=True), boxes.to_mask(10, 10)
+
+ def written(x, y, z):
+ boxes = Boxes.from_tensor([x, y], mode="xyxy", validate_boxes=False)
+ boxes[0, 1:2] = Boxes(z)
+ merged = boxes.merge(Boxes(z.expand(2, -1, -1, -1)))
+ return merged.to_tensor("xyxy"), merged.to_tensor("xyxy", as_padded_sequence=True), merged.to_mask(10, 10)
+
+ for function, args in ((untouched, (first, second)), (written, (first, second, new))):
+ exported, padded, masks = torch_optimizer(function, fullgraph=True)(*args)
+ expected_exported, expected_padded, expected_masks = function(*args)
+ assert len(exported) == len(expected_exported)
+ for actual, expected in zip(exported, expected_exported):
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+ self.assert_close(padded, expected_padded, atol=0.0, rtol=0.0)
+ self.assert_close(masks, expected_masks, atol=0.0, rtol=0.0)
+
@pytest.mark.parametrize("key_kind", ["first", "last", "scalar_tensor"])
def test_scalar_selection_keeps_validity_in_step_6478(
self,
@@ -2517,6 +3049,126 @@ class TestVideoBoxes(BaseTester):
assert video.to_tensor("xyxy")[1, :, 1].count_nonzero() > 0
assert filtered.to_mask(5, 5)[:, :, 1].count_nonzero() == 0
+ @staticmethod
+ def _padding_frames(device, dtype):
+ # Four frames with one, two, one and one boxes.
+ corners = torch.tensor([[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]], device=device, dtype=dtype)
+ return corners, Boxes([corners[None], torch.stack([corners, corners + 2]), corners[None], corners[None]])
+
+ @pytest.mark.parametrize("inplace", [False, True])
+ def test_merge_with_list_boxes_marks_the_padding_invalid_6283(self, inplace, device, dtype):
+ # A VideoBoxes has no ragged export: frames with different box counts share one (B, T, N, ...) tensor. The
+ # padding of merged list boxes is therefore invalid: exact zero rows in every mode and no mask, also after a
+ # transform.
+ corners, frames = self._padding_frames(device, dtype)
+ video = VideoBoxes.from_tensor(corners.reshape(1, 1, 1, 4, 2).repeat(2, 2, 1, 1, 1))
+ merged = video.merge(frames, inplace=inplace)
+ assert (merged is video) == inplace
+ assert isinstance(merged, VideoBoxes)
+ assert merged._N is None
+ assert merged.temporal_channel_size == 2
+
+ padding = torch.tensor([[[0, 0, 1], [0, 0, 0]], [[0, 0, 1], [0, 0, 1]]], device=device, dtype=torch.bool)
+ rows = torch.stack([corners] * 3).expand(4, 3, 4, 2).clone()
+ rows[1, 2] = corners + 2
+ dense = Boxes(rows, False)
+ transform = torch.eye(3, device=device, dtype=dtype)
+ transform[:2, 2] = 1.0
+ for boxes, reference in (
+ (merged, dense),
+ (merged.transform_boxes(transform.expand(4, -1, -1)), dense.transform_boxes(transform.expand(4, -1, -1))),
+ ):
+ for mode in ("xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"):
+ exported = boxes.to_tensor(mode)
+ expected = reference.to_tensor(mode).reshape(exported.shape)
+ assert exported.shape[:3] == (2, 2, 3)
+ assert exported[padding].count_nonzero() == 0
+ self.assert_close(exported[~padding], expected[~padding], atol=0.0, rtol=0.0)
+ self.assert_close(boxes[1:].to_tensor(mode), exported[1:], atol=0.0, rtol=0.0)
+ self.assert_close(boxes[0].to_tensor(mode), exported[:1], atol=0.0, rtol=0.0)
+ masks = boxes.to_mask(8, 8)
+ assert masks.shape == (2, 2, 3, 8, 8)
+ assert masks[padding].count_nonzero() == 0
+ assert masks[~padding].flatten(1).any(dim=1).all()
+ expected_masks = reference.to_mask(8, 8).reshape(masks.shape)
+ self.assert_close(masks[~padding], expected_masks[~padding], atol=0.0, rtol=0.0)
+
+ def test_list_constructor_keeps_no_padding_6283(self, device, dtype):
+ corners, _ = self._padding_frames(device, dtype)
+ video = VideoBoxes([corners[None], torch.stack([corners, corners + 2])], False)
+ video.temporal_channel_size = 1
+ assert video._N is None
+ exported = video.to_tensor("xyxy")
+ assert exported.shape == (2, 1, 2, 4)
+ assert exported[0, 0, 1].count_nonzero() == 0
+ assert exported[1, 0, 1].count_nonzero() > 0
+
+ def test_integer_video_selection_shares_nothing_6283(self, device):
+ from kornia.augmentation.utils.helpers import _frame_boxes
+
+ boxes = VideoBoxes.from_tensor(torch.ones(2, 3, 1, 4, 2, device=device)).type(torch.long)
+ for derived in (boxes[0], _frame_boxes(boxes)):
+ assert derived.data.is_floating_point()
+ assert not _same_storage(derived.data, boxes.data)
+ assert not _same_storage(derived._valid, boxes._valid)
+
+ @pytest.mark.parametrize(
+ "rebind",
+ [
+ pytest.param(lambda b: b.to(dtype=_other_dtype(b.dtype)), id="to_dtype"),
+ pytest.param(lambda b: b.type(_other_dtype(b.dtype)), id="type_dtype"),
+ pytest.param(lambda b: b.transform_boxes_(_identity(b)), id="transform_boxes_"),
+ pytest.param(lambda b: b.transform_boxes(_identity(b), inplace=True), id="transform_boxes"),
+ pytest.param(lambda b: b.translate(_bounds(b, 0.0), inplace=True), id="translate"),
+ ],
+ )
+ def test_view_validity_follows_its_coordinates_6283(self, rebind, device, dtype):
+ # The validity of a selection stops being shared when its coordinates do, or invalidating its rows, as filtering
+ # does, would blank rows of the parent whose coordinates it no longer reaches.
+ corners, _ = self._padding_frames(device, dtype)
+ video = VideoBoxes.from_tensor(corners.reshape(1, 1, 1, 4, 2).repeat(2, 2, 2, 1, 1))
+ before = video.to_tensor("xyxy").clone()
+ selected = video[0]
+ rebind(selected)
+ selected._valid[:] = False
+ self.assert_close(video.to_tensor("xyxy"), before, atol=0.0, rtol=0.0)
+ assert selected.to_tensor("xyxy").count_nonzero() == 0
+
+ def test_merge_with_list_boxes_keeps_the_batch_check_6283(self, device, dtype):
+ corners, frames = self._padding_frames(device, dtype)
+ video = VideoBoxes.from_tensor(corners.reshape(1, 1, 1, 4, 2).repeat(1, 2, 1, 1, 1))
+ with pytest.raises(ValueError, match="Batch size mismatch"):
+ video.merge(frames)
+
+ @pytest.mark.parametrize("write", ["setitem", "index_put"])
+ def test_writing_list_boxes_marks_the_padding_invalid_6283(self, write, device, dtype):
+ corners, frames = self._padding_frames(device, dtype)
+ video = VideoBoxes.from_tensor(corners.reshape(1, 1, 1, 4, 2).repeat(2, 2, 2, 1, 1))
+ if write == "setitem":
+ video[0] = frames[:2]
+ else:
+ video.index_put((torch.tensor([0], device=device),), frames[0:1], inplace=True)
+ assert video._N is None
+ assert video.to_tensor("xyxy")[0, 0, 1].count_nonzero() == 0
+ assert video.to_tensor("xyxy")[0, 0, 0].count_nonzero() > 0
+ masks = video.to_mask(8, 8)
+ assert masks[0, 0, 1].count_nonzero() == 0
+ assert masks[0, 0, 0].count_nonzero() > 0
+ assert masks[1].flatten(2).any(dim=2).all()
+
+ def test_unpickle_with_padding_counts_6283(self, device, dtype):
+ # An earlier kornia could leave counts on a VideoBoxes after a merge; they load as invalid rows, which export.
+ corners, _ = self._padding_frames(device, dtype)
+ video = VideoBoxes.from_tensor(corners.reshape(1, 1, 1, 4, 2).repeat(1, 2, 2, 1, 1))
+ video.__dict__.pop("_padding", None)
+ video.__dict__["_N"] = [1, 0]
+ restored = pickle.loads(pickle.dumps(video)) # noqa: S301
+ assert restored._N is None
+ exported = restored.to_tensor("xyxy")
+ assert exported.shape == (1, 2, 2, 4)
+ assert exported[0, 0, 1].count_nonzero() == 0
+ assert exported[0, 1, 1].count_nonzero() > 0
+
"""Public API and round-trip coverage for :class:`VideoBoxes` (#4016)."""
@staticmethod