# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from __future__ import annotations

from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union

import torch
import torch.nn.functional as F
from torch import nn

import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils.helpers import _raise_input_rank_error
from kornia.contrib.extract_patches import extract_tensor_patches
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.ops import _device_literal
from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints

from .base import SequentialBase
from .image import ImageSequential
from .ops import InputSequentialOps
from .params import ParamItem, PatchParamItem

__all__ = ["PatchSequential"]


def _patch_indices(indices: Union[List[int], torch.Tensor], device: torch.device) -> torch.Tensor:
    """Return the patch ``indices`` as a long tensor on ``device``, without a host-to-device copy that waits.

    Indexing a CUDA tensor with a Python list copies the list to the device and waits for every queued kernel.
    ``forward_parameters`` stores evenly spaced indices, which ``torch.arange`` builds on the device; any other list is
    a device literal. Both index exactly the patches the list names.
    """
    if isinstance(indices, torch.Tensor):
        return _to_device_nonblocking(indices, device)
    values = [int(i) for i in indices]
    if len(values) > 1:
        step = values[1] - values[0]
        if step > 0 and all(v == values[0] + k * step for k, v in enumerate(values)):
            return torch.arange(values[0], values[-1] + 1, step, device=device)
    return _device_literal(values, device=device, dtype=torch.long)


class PatchSequential(ImageSequential):
    r"""Apply image transforms independently to a regular grid of image patches.

    ``output = PatchSequential(*modules, grid_size=...)(input)`` splits each image into a grid, runs the configured
    children on the patch batch, then joins the patches.

    See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.

    .. image:: _static/img/PatchSequential.png

    Processing runs on each patch region as in :cite:`lin2021patch`.

    Args:
        *args: a list of processing modules.
        grid_size: positive ``(rows, columns)`` of patches in each image.
        padding: ``"same"`` temporarily zero-pads to a multiple of ``grid_size`` and removes the added
            border after augmentation, preserving the input spatial size. ``"valid"`` crops the remainder
            before augmentation and keeps the cropped spatial size. Padding and cropping are centered;
            an odd extra pixel is placed on the right or bottom. Both modes preserve the batch size.
            Geometric transforms can move the temporary zero border into the retained image; removing
            the added border does not undo that movement.
        same_on_batch: apply the same transformation across the batch.
            If None, it will not overwrite the function-wise settings.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
            to the batch form (False). If None, it will not overwrite the function-wise settings.
        patchwise_apply: apply image processing args will be applied patch-wisely.
            if ``True`` and ``random_apply=False``, the number of args must equal the number of patches.
            if ``False``, the image processing args will be applied as a sequence to all patches.
        random_apply: randomly select children to apply in random order. Selections repeat when the requested count is
            larger than the number of children that can be drawn: the children with a nonzero selection weight, mix
            augmentations not counted, plus one place when the count and the mix augmentations together reach the number
            of children, since a mix augmentation is then certain to take a place. With only mix children one of them is
            drawn, and with all weights 0 and no mix child nothing is.
            An int or a range that is not fixed to the number of children also repeats when the drawn count is larger
            than the sum of the weights. That rule is deprecated since kornia 0.9.1, with a ``FutureWarning`` on the
            calls whose draw it changes, as in :class:`~kornia.augmentation.container.ImageSequential`.
            If ``int`` (batchwise mode only), a fixed number of transformations will be selected.
            If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected.
            If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected.
            If ``True`` and not ``patchwise_apply``, the whole list of args will be processed in a random order,
            whatever the scale of the weights, and so will a count fixed to the number of children. With a non-mix child
            of weight 0 or more than one mix augmentation, that count cannot be filled: children repeat and some may be
            left out.
            If ``True`` and ``patchwise_apply``, 1 to 4 transformations will be selected per patch, a range under the
            deprecated rule above. Once a patch has drawn a mix augmentation, later patches count no place for one.
            If ``False`` and not ``patchwise_apply``, the whole list of args will be processed in original order.
            If ``False`` and ``patchwise_apply``, the whole list of args will be processed in original order
            location-wisely.
        random_apply_weights: selection weights for each child, as in
            :class:`~kornia.augmentation.container.ImageSequential`.

    Convention:
        - like :class:`~kornia.augmentation.container.ImageSequential`, this container takes image tensors only: it has
          no ``data_keys`` and no ``.transform_matrix`` attribute.
        - input images have shape ``(B, C, H, W)``. Each image is split into ``N = rows * columns`` patches,
          ordered by row then column. Parameters index the flattened ``B * N`` patch batch.
        - with ``patchwise_apply=True`` and ``random_apply=False``, each module processes its grid location
          across all images. ``same_on_batch`` controls parameter sharing, not which images are processed.
        - with ``patchwise_apply=False``, the selected sequence is applied to every patch.
        - an empty image batch retains the grid's patch count and spatial sizes. Children must themselves
          support empty inputs; geometric patch inverses and mask transforms remain unsupported.
        - ``padding="valid"`` requires at least one pixel per patch in each spatial dimension. For example,
          an ``8 x 8`` image on a ``(3, 3)`` grid remains ``8 x 8`` with ``"same"`` and becomes ``6 x 6``
          with ``"valid"``. The batch size, channel count, device and dtype are preserved.

    .. note::
        Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
        Those transformations in ``kornia.geometry`` will not be taken into account.

    .. note::
        See a working example `here <https://www.kornia.org/tutorials/nbs/data_patch_sequential.html>`__.

    .. warning::
        Under ``torch.compile`` with the default inductor backend, torch earlier than 2.15 returns wrong values when a
        child reads the patches at other positions, a flip for example, after an earlier child has written them
        (`pytorch/pytorch#198270 <https://github.com/pytorch/pytorch/issues/198270>`__). Eager execution,
        the ``aot_eager`` backend and torch 2.15 or later are not affected.

    See Also:
        - :class:`~kornia.augmentation.container.ImageSequential`: applies its child sequence to whole images.
        - :class:`~kornia.augmentation.container.AugmentationSequential`: transforms images with aligned annotations.

    Examples:
        >>> import kornia.augmentation as K
        >>> input = torch.randn(2, 3, 224, 224)
        >>> seq = PatchSequential(
        ...     ImageSequential(
        ...         K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),
        ...         K.RandomPerspective(0.2, p=0.5),
        ...         K.RandomSolarize(0.1, 0.1, p=0.5),
        ...     ),
        ...     K.RandomAffine(360, p=1.0),
        ...     ImageSequential(
        ...         K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),
        ...         K.RandomPerspective(0.2, p=0.5),
        ...         K.RandomSolarize(0.1, 0.1, p=0.5),
        ...     ),
        ...     K.RandomSolarize(0.1, 0.1, p=0.1),
        ...     grid_size=(2,2),
        ...     patchwise_apply=True,
        ...     same_on_batch=True,
        ...     random_apply=False,
        ... )
        >>> out = seq(input)
        >>> out.shape
        torch.Size([2, 3, 224, 224])
        >>> out1 = seq(input, params=seq._params)
        >>> torch.equal(out, out1)
        True

    Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``PatchSequential``.

        >>> import kornia
        >>> input = torch.randn(2, 3, 224, 224)
        >>> seq = PatchSequential(
        ...     ImageSequential(
        ...         K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),
        ...         K.RandomPerspective(0.2, p=0.5),
        ...         K.RandomSolarize(0.1, 0.1, p=0.5),
        ...     ),
        ...     K.RandomAffine(360, p=1.0),
        ...     K.RandomSolarize(0.1, 0.1, p=0.1),
        ...     grid_size=(2,2),
        ...     patchwise_apply=False,
        ...     random_apply=1,
        ...     random_apply_weights=[0.5, 0.3, 0.8]
        ... )
        >>> out = seq(input)
        >>> out.shape
        torch.Size([2, 3, 224, 224])

    """

    def __init__(
        self,
        *args: nn.Module,
        grid_size: Tuple[int, int] = (4, 4),
        padding: str = "same",
        same_on_batch: Optional[bool] = None,
        keepdim: Optional[bool] = None,
        patchwise_apply: bool = True,
        random_apply: Union[int, bool, Tuple[int, int]] = False,
        random_apply_weights: Optional[Union[Sequence[float], torch.Tensor]] = None,
    ) -> None:
        _random_apply: Optional[Union[int, Tuple[int, int]]]

        self._validate_grid_size(grid_size)

        if patchwise_apply and random_apply is True:
            # will only apply [1, 4] augmentations per patch
            _random_apply = (1, 4)
        elif patchwise_apply and random_apply is False:
            if len(args) != grid_size[0] * grid_size[1]:
                raise ValueError(
                    "The number of processing modules must be equal with grid size."
                    f"Got {len(args)} and {grid_size[0] * grid_size[1]}. "
                    "Please set random_apply = True or patchwise_apply = False."
                )
            _random_apply = random_apply
        elif patchwise_apply and isinstance(random_apply, (int, tuple)):
            raise ValueError(f"Only boolean value allowed when `patchwise_apply` is set to True. Got {random_apply}.")
        else:
            _random_apply = random_apply
        super().__init__(
            *args,
            same_on_batch=same_on_batch,
            keepdim=keepdim,
            random_apply=_random_apply,
            random_apply_weights=random_apply_weights,
        )
        if padding not in ("same", "valid"):
            raise ValueError(f"`padding` must be either `same` or `valid`. Got {padding}.")
        self.grid_size = grid_size
        self.padding = padding
        self.patchwise_apply = patchwise_apply
        self._params: Optional[List[PatchParamItem]]

    @staticmethod
    def _validate_grid_size(grid_size: Tuple[int, int]) -> None:
        if (
            not isinstance(grid_size, (tuple, list))
            or len(grid_size) != 2
            or any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in grid_size)
        ):
            raise ValueError(f"grid_size must contain two positive integers. Got {grid_size}.")

    def compute_padding(
        self, input: torch.Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
    ) -> Tuple[int, int, int, int]:
        """Compute spatial padding needed before patch extraction.

        Args:
            input: Input image tensor.
            padding: Padding mode, either ``"same"`` or ``"valid"``.
            grid_size: Optional grid override. Uses ``self.grid_size`` when omitted.

        Returns:
            Padding tuple ``(left, right, top, bottom)``. Negative values crop the border.

        Raises:
            ValueError: The input is not four-dimensional, has an empty spatial dimension, or the
                grid cannot produce non-empty patches in ``"valid"`` mode.
            NotImplementedError: ``padding`` is neither ``"same"`` nor ``"valid"``.
        """
        return self._compute_padding(input.shape, padding, grid_size)

    def _compute_padding(
        self, batch_shape: torch.Size, padding: str, grid_size: Optional[Tuple[int, int]] = None
    ) -> Tuple[int, int, int, int]:
        """Compute padding from an image shape without allocating a tensor."""
        if grid_size is None:
            grid_size = self.grid_size
        self._validate_grid_size(grid_size)
        if len(batch_shape) != 4:
            _raise_input_rank_error(batch_shape, "(B, C, H, W)")
        height, width = batch_shape[-2:]
        if height <= 0 or width <= 0:
            raise ValueError("PatchSequential requires non-empty spatial dimensions.")
        if padding == "valid":
            if height < grid_size[0] or width < grid_size[1]:
                raise ValueError("grid_size must produce non-empty patches with padding='valid'.")
            ph, pw = height % grid_size[0], width % grid_size[1]
            return (-(pw // 2), -(pw - pw // 2), -(ph // 2), -(ph - ph // 2))
        if padding == "same":
            ph, pw = -height % grid_size[0], -width % grid_size[1]
            return (pw // 2, pw - pw // 2, ph // 2, ph - ph // 2)
        raise NotImplementedError(f"Expect `padding` as either 'valid' or 'same'. Got {padding}.")

    def extract_patches(
        self,
        input: torch.Tensor,
        grid_size: Optional[Tuple[int, int]] = None,
        pad: Optional[Tuple[int, int, int, int]] = None,
    ) -> torch.Tensor:
        """Extract ``(B, rows * columns, C, h, w)`` patches from an image batch.

        The spatial size after applying ``pad`` must be positive and divisible by ``grid_size``.
        Use :meth:`compute_padding` to determine the padding or cropping for a given mode.

        Example:
            >>> import kornia.augmentation as K
            >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)
            >>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
            tensor([[[[[ 0,  1],
                       [ 4,  5]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[ 2,  3],
                       [ 6,  7]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[ 8,  9],
                       [12, 13]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[10, 11],
                       [14, 15]]]]])
            >>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -2, -2, -2))
            tensor([[[[[19, 20, 21]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[22, 23, 24]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[28, 29, 30]]],
            <BLANKLINE>
            <BLANKLINE>
                     [[[31, 32, 33]]]]])

        """
        if grid_size is None:
            grid_size = self.grid_size
        self._validate_grid_size(grid_size)
        if input.ndim != 4:
            _raise_input_rank_error(input.shape, "(B, C, H, W)")
        height, width = input.shape[-2:]
        if pad is not None:
            height, width = height + pad[2] + pad[3], width + pad[0] + pad[1]
        if height <= 0 or width <= 0 or height % grid_size[0] or width % grid_size[1]:
            raise ValueError(
                f"Padded image size {(height, width)} must be positive and divisible by grid_size {grid_size}."
            )
        if pad is not None:
            input = F.pad(input, list(pad))
        window_size = (input.size(-2) // grid_size[-2], input.size(-1) // grid_size[-1])
        stride = window_size
        return extract_tensor_patches(input, window_size, stride)

    def restore_from_patches(
        self,
        patches: torch.Tensor,
        grid_size: Optional[Tuple[int, int]] = None,
        pad: Optional[Tuple[int, int, int, int]] = None,
    ) -> torch.Tensor:
        """Restore images from ``(B, rows * columns, C, h, w)`` patches.

        Uses ``self.grid_size`` unless overridden. Only positive entries in ``pad`` are removed:
        pixels cropped during extraction cannot be recovered and are not replaced with zeroes.

        Example:
            >>> import kornia.augmentation as K
            >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)
            >>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))
            >>> pas.restore_from_patches(out, grid_size=(2, 2))
            tensor([[[[ 0,  1,  2,  3],
                      [ 4,  5,  6,  7],
                      [ 8,  9, 10, 11],
                      [12, 13, 14, 15]]]])

        """
        if grid_size is None:
            grid_size = self.grid_size
        self._validate_grid_size(grid_size)
        KORNIA_CHECK_SHAPE(patches, ["B", "N", "C", "H", "W"])
        batch, count, channels, height, width = patches.shape
        if count != grid_size[0] * grid_size[1]:
            raise ValueError(f"The patch count {count} must equal grid_size[0] * grid_size[1] for {grid_size}.")
        patches_tensor = patches.reshape(batch, grid_size[0], grid_size[1], channels, height, width)
        restored_tensor = patches_tensor.permute(0, 3, 1, 4, 2, 5).reshape(
            batch, channels, grid_size[0] * height, grid_size[1] * width
        )

        if pad is not None:
            restored_tensor = F.pad(restored_tensor, [-max(i, 0) for i in pad])
        return restored_tensor

    def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]:
        """Generate patch-level parameters for a forward pass.

        Args:
            batch_shape: Image shape ``(B, C, H, W)`` or extracted patch shape ``(B, N, C, h, w)``,
                with ``N = grid_size[0] * grid_size[1]``. Image shapes are converted to patch shapes
                using this container's ``grid_size`` and ``padding`` without allocating an image.

        Returns:
            List of :class:`PatchParamItem` entries, including patch indices and
            operation params.

        Example:
            >>> seq = PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=(2, 3), patchwise_apply=False)
            >>> image = torch.rand(2, 3, 5, 7)
            >>> params = seq.forward_parameters(image.shape)
            >>> output = seq(image, params=params)
            >>> torch.equal(output, seq(image, params=params))
            True
        """
        if len(batch_shape) == 4:
            left, right, top, bottom = self._compute_padding(batch_shape, self.padding)
            batch, channels, height, width = batch_shape
            batch_shape = torch.Size(
                (
                    batch,
                    self.grid_size[0] * self.grid_size[1],
                    channels,
                    (height + top + bottom) // self.grid_size[0],
                    (width + left + right) // self.grid_size[1],
                )
            )
        if len(batch_shape) != 5:
            _raise_input_rank_error(batch_shape, "either (B, C, H, W) or (B, rows * columns, C, h, w)")
        if batch_shape[1] != self.grid_size[0] * self.grid_size[1]:
            raise ValueError(
                f"Expected image shape (B, C, H, W) or patch shape (B, rows * columns, C, h, w). Got {batch_shape}."
            )
        out_param: List[PatchParamItem] = []
        if not self.patchwise_apply:
            params = self.generate_parameters(torch.Size([1, batch_shape[0] * batch_shape[1], *batch_shape[2:]]))
            indices = torch.arange(0, batch_shape[0] * batch_shape[1])
            out_param = [PatchParamItem(indices.tolist(), p) for p, _ in params]
        elif not self.same_on_batch and self.random_apply:
            params = self.generate_parameters(torch.Size([batch_shape[0] * batch_shape[1], 1, *batch_shape[2:]]))
            out_param = [PatchParamItem([i], p) for p, i in params]
        else:
            # Fixed locations draw B parameters together, respecting the child's same_on_batch setting.
            params = self.generate_parameters(torch.Size([batch_shape[1], batch_shape[0], *batch_shape[2:]]))
            indices = torch.arange(0, batch_shape[0] * batch_shape[1], step=batch_shape[1])
            out_param = [PatchParamItem((indices + i).tolist(), p) for p, i in params]
        return out_param

    def generate_parameters(self, batch_shape: torch.Size) -> Iterator[Tuple[ParamItem, int]]:
        """Get multiple forward sequence but maximumly one mix augmentation in between.

        Args:
            batch_shape: 5-dim shape arranged as :math:``(N, B, C, H, W)``, in which N represents
                the number of sequence.

        """
        if self.random_apply:
            # A mix augmentation may be drawn until one has been added, so at most one is applied in this call.
            with_mix = True
            for i in range(batch_shape[0]):
                seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
                with_mix = with_mix and not mix_added
                for s in seq:
                    if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
                        yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i
                    else:
                        yield ParamItem(s[0], None), i
        else:
            for i, nchild in enumerate(self.named_children()):
                if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
                    yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i
                else:
                    yield ParamItem(nchild[0], None), i

    def forward_by_params(self, input: torch.Tensor, params: List[PatchParamItem]) -> torch.Tensor:
        """Apply module parameters to selected patch indices.

        Args:
            input: Tensor of extracted patches.
            params: Patch operation payloads with ``indices`` and per-module params.

        Returns:
            Augmented patch tensor.
        """
        in_shape = input.shape
        input = input.reshape(-1, *in_shape[-3:])

        for patch_param in params:
            # input, out_param = self.apply_by_param(input, params=patch_param)
            module = self.get_submodule(patch_param.param.name)
            indices = _patch_indices(patch_param.indices, input.device)
            _input = input[indices]
            output = InputSequentialOps.transform(_input, module, patch_param.param, extra_args={})
            # Mix operations may promote to their parameter dtype; the patch buffer retains the image dtype.
            input[indices] = output.to(input)

        return input.reshape(in_shape)

    def transform_inputs(
        self, input: torch.Tensor, params: Optional[List[PatchParamItem]], extra_args: Optional[Dict[str, Any]] = None
    ) -> torch.Tensor:
        """Apply patch-wise augmentation to an input tensor.

        Args:
            input: Input image tensor.
            params: Patch-level parameters from :meth:`forward_parameters`, or ``None`` to generate them.
            extra_args: Optional runtime overrides (unused in this implementation).

        Returns:
            Augmented image tensor after extract-transform-restore.
        """
        pad = self.compute_padding(input, self.padding)
        input = self.extract_patches(input, self.grid_size, pad)
        if params is None:
            params = self.forward_parameters(input.shape)
        input = self.forward_by_params(input, params)
        input = self.restore_from_patches(input, self.grid_size, pad=pad)
        self._params = params

        return input

    def inverse_inputs(
        self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> torch.Tensor:
        """Inverse the patch pipeline when supported.

        Args:
            input: Augmented image tensor.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Original tensor for intensity-only pipelines.

        Raises:
            NotImplementedError: Geometric patch pipelines cannot be inverted.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")

    def transform_masks(
        self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> torch.Tensor:
        """Transform masks for intensity-only patch pipelines.

        Args:
            input: Input mask tensor.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Unchanged mask tensor when the pipeline is intensity-only.

        Raises:
            NotImplementedError: Geometric patch pipelines are unsupported for masks.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")

    def inverse_masks(
        self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> torch.Tensor:
        """Inverse mask transforms for supported patch pipelines.

        Args:
            input: Augmented mask tensor.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Original mask tensor for intensity-only pipelines.

        Raises:
            NotImplementedError: Geometric patch pipelines cannot be inverted.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")

    def transform_boxes(
        self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> Boxes:
        """Transform boxes for intensity-only patch pipelines.

        Args:
            input: Input boxes.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Unchanged boxes when the pipeline is intensity-only.

        Raises:
            NotImplementedError: Geometric patch pipelines are unsupported for boxes.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")

    def inverse_boxes(
        self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> Boxes:
        """Inverse box transforms for supported patch pipelines.

        Args:
            input: Augmented boxes.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Original boxes for intensity-only pipelines.

        Raises:
            NotImplementedError: Geometric patch pipelines cannot be inverted.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")

    def transform_keypoints(
        self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> Keypoints:
        """Transform keypoints for intensity-only patch pipelines.

        Args:
            input: Input keypoints.
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Unchanged keypoints when the pipeline is intensity-only.

        Raises:
            NotImplementedError: Geometric patch pipelines are unsupported for keypoints.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential for keypoints cannot be used with geometric transformations.")

    def inverse_keypoints(
        self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
    ) -> Keypoints:
        """Inverse keypoint transforms for supported patch pipelines.

        Args:
            input: Augmented keypoints (conceptually ``(B, N, 2)`` coordinates,
                where the last dimension stores ``(x, y)``).
            params: Parameters used during forward.
            extra_args: Optional runtime overrides.

        Returns:
            Original keypoints for intensity-only pipelines.

        Raises:
            NotImplementedError: Geometric patch pipelines cannot be inverted.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")

    def inverse(
        self,
        input: torch.Tensor,
        params: Optional[List[PatchParamItem]] = None,
        extra_args: Optional[Dict[str, Any]] = None,
    ) -> torch.Tensor:
        """Inverse transformation.

        Used to inverse a torch.Tensor according to the performed transformation by a forward pass, or with respect to
        provided parameters.
        """
        if self.is_intensity_only():
            return input

        raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")

    def forward(self, input: torch.Tensor, params: Optional[List[PatchParamItem]] = None) -> torch.Tensor:
        """Augment an image batch, optionally replaying previously generated patch parameters."""
        if isinstance(input, (tuple,)):
            raise ValueError("tuple input is not currently supported.")

        return self.transform_inputs(input, params=params)
