Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs: add missing docstrings to augmentation module (#3666)

Jeevang1-epicc6c108f7d37d
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 0d407689f..74f739c77 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -156,9 +156,26 @@ class AutoAugment(PolicyAugmentBase):
self.rand_selector = Categorical(selection_weights)
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
+ """Build a :class:`PolicySequential` from one AutoAugment sub-policy.
+
+ Args:
+ subpolicy: Sequence of ``(name, probability, magnitude)`` operation tuples.
+
+ Returns:
+ A sequential container that applies the configured operations in order.
+ """
return PolicySequential(*[getattr(ops, name)(prob, mag) for name, prob, mag in subpolicy])
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ """Return the operations to run for the current forward call.
+
+ Args:
+ params: Optional recorded parameters. When provided, the sequence is
+ reconstructed from them.
+
+ Returns:
+ Iterator of ``(name, module)`` pairs.
+ """
if params is None:
idx = self.rand_selector.sample((1,))
return self.get_children_by_indices(idx)
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 49cd0d1ce..3487dac10 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -45,6 +45,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
self._transform_matrices.append(module.transform_matrix)
def clear_state(self) -> None:
+ """Reset cached params and transformation-matrix state."""
self._reset_transform_matrix_state()
return super().clear_state()
@@ -53,6 +54,14 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return [self.compose_subpolicy_sequential(subpolicy) for subpolicy in policy]
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
+ """Build a :class:`PolicySequential` from a single sub-policy spec.
+
+ Args:
+ subpolicy: Sub-policy definition used by the concrete augmentation.
+
+ Returns:
+ The sequential module representing that sub-policy.
+ """
raise NotImplementedError
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
@@ -91,6 +100,14 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return res_mat
def is_intensity_only(self, params: Optional[List[ParamItem]] = None) -> bool:
+ """Check whether all selected sub-policies are intensity-only.
+
+ Args:
+ params: Optional parameters that define which sub-policies to inspect.
+
+ Returns:
+ ``True`` if no geometric transform is selected, ``False`` otherwise.
+ """
named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
for _, module in named_modules:
module = cast(PolicySequential, module)
@@ -99,6 +116,14 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
return True
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Generate per-module parameters for one policy forward pass.
+
+ Args:
+ batch_shape: Input shape used to sample operation parameters.
+
+ Returns:
+ Parameters for each selected child module, in execution order.
+ """
named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
@@ -113,6 +138,16 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
def transform_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply a prepared parameter list to the input tensor.
+
+ Args:
+ input: Input tensor.
+ params: Parameters produced by :meth:`forward_parameters`.
+ extra_args: Optional overrides forwarded to child transforms.
+
+ Returns:
+ Transformed tensor.
+ """
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
@@ -121,6 +156,17 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
def forward(
self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply the policy to ``input`` and cache the parameters used.
+
+ Args:
+ input: Input tensor.
+ params: Optional precomputed parameters. If omitted, parameters are
+ sampled on-the-fly.
+ extra_args: Optional overrides forwarded to child transforms.
+
+ Returns:
+ Augmented tensor.
+ """
self.clear_state()
if params is None:
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 868d9d55e..3edcb9b64 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -129,27 +129,47 @@ class OperationBase(nn.Module):
self.op._p_gen = Bernoulli(self.probability)
def train(self, mode: bool = True) -> Self:
- self._update_probability_gen(relaxation=mode)
+ """Switch training mode and refresh probability samplers.
+
+ Args:
+ mode: ``True`` for training mode, ``False`` for evaluation mode.
+ Returns:
+ This module.
+ """
+ self._update_probability_gen(relaxation=mode)
return super().train(mode=mode)
def eval(self) -> Self:
+ """Switch to evaluation mode.
+
+ Returns:
+ This module.
+ """
return self.train(False)
def forward_parameters(
self, batch_shape: torch.Size, mag: Optional[torch.Tensor] = None
) -> Dict[str, torch.Tensor]:
+ """Sample parameters for the wrapped augmentation op.
+
+ Args:
+ batch_shape: Input batch shape used for sampling.
+ mag: Optional magnitude override. When set, it replaces the sampled
+ factor before the magnitude mapping function is applied.
+
+ Returns:
+ Parameter dictionary consumed by :meth:`forward`.
+ """
if mag is None:
mag = self.magnitude
- # Need to setup the sampler again for each update.
- # Otherwise, an error for updating the same graph twice will be thrown.
+
self._update_probability_gen(relaxation=True)
params = self.op.forward_parameters(batch_shape)
if mag is not None:
if self._factor_name is None:
raise RuntimeError("No factor found in the params while `mag` is provided.")
- # For single factor operations, this is equivalent to `same_on_batch=True`
params[self._factor_name] = params[self._factor_name].zero_() + mag
if self._factor_name is not None:
@@ -158,6 +178,17 @@ class OperationBase(nn.Module):
return params
def forward(self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None) -> torch.Tensor:
+ """Apply the operation with probabilistic gating.
+
+ Args:
+ input: Input tensor.
+ params: Optional precomputed parameters. If omitted, parameters are
+ sampled from ``input.shape``.
+
+ Returns:
+ Tensor where each sample is either transformed or left unchanged
+ according to ``batch_prob``.
+ """
if params is None:
params = self.forward_parameters(input.shape)
@@ -167,12 +198,24 @@ class OperationBase(nn.Module):
@property
def transform_matrix(self) -> Optional[torch.Tensor]:
+ """Return the latest transform matrix from the wrapped op, if available.
+
+ Returns:
+ Transform matrix tensor or ``None`` for non-geometric operations.
+ """
if hasattr(self.op, "transform_matrix"):
return self.op.transform_matrix
return None
@property
def magnitude(self) -> Optional[torch.Tensor]:
+ """Return the learned magnitude value for the operation.
+
+ Returns:
+ Magnitude tensor, clamped to ``magnitude_range`` when defined; otherwise
+ the raw learnable value. Returns ``None`` when this operation has no
+ magnitude parameter.
+ """
if self._magnitude is None:
return None
mag = self._magnitude
@@ -182,5 +225,10 @@ class OperationBase(nn.Module):
@property
def probability(self) -> torch.Tensor:
+ """Return the operation probability after applying configured bounds.
+
+ Returns:
+ Probability tensor clamped to ``probability_range``.
+ """
p = self._probability.clamp(*self.probability_range)
return p
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 342d70040..5c1566ddb 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -46,10 +46,19 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
self._transform_matrices.append(module.transform_matrix)
def clear_state(self) -> None:
+ """Reset cached params and transformation-matrix state."""
self._reset_transform_matrix_state()
return super().clear_state()
def validate_operations(self, *operations: OperationBase) -> None:
+ """Ensure all provided modules are :class:`OperationBase` instances.
+
+ Args:
+ *operations: Operations passed to :class:`PolicySequential`.
+
+ Raises:
+ ValueError: Any provided operation is not a Kornia auto operation.
+ """
invalid_ops: List[OperationBase] = []
for op in operations:
if not isinstance(op, OperationBase):
@@ -104,6 +113,11 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
return res_mat
def is_intensity_only(self) -> bool:
+ """Check whether the policy contains only intensity transforms.
+
+ Returns:
+ ``True`` when no geometric operation is present.
+ """
for module in self.children():
module = cast(OperationBase, module)
if isinstance(module.op, (K.GeometricAugmentationBase2D,)):
@@ -111,11 +125,28 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
return True
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ """Return the operation sequence used for execution.
+
+ Args:
+ params: Optional recorded parameters. When provided, only modules
+ referenced by those params are returned.
+
+ Returns:
+ Iterator of ``(name, module)`` pairs.
+ """
if params is not None:
return super().get_children_by_params(params)
return self.named_children()
def forward_parameters(self, batch_shape: Size) -> List[ParamItem]:
+ """Generate parameter dictionaries for each operation in the policy.
+
+ Args:
+ batch_shape: Input shape used to sample operation parameters.
+
+ Returns:
+ List of :class:`ParamItem` objects in execution order.
+ """
named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
@@ -130,6 +161,16 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
def transform_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply all operations using a prepared parameter list.
+
+ Args:
+ input: Input tensor.
+ params: Parameters for each operation in this policy.
+ extra_args: Optional overrides forwarded to child modules.
+
+ Returns:
+ Transformed tensor.
+ """
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index a8d7eda09..20647e48e 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -91,26 +91,61 @@ class RandAugment(PolicyAugmentBase):
self.m = m
def rand_selector(self, n: int) -> torch.Tensor:
+ """Randomly choose ``n`` policy indices without replacement.
+
+ Args:
+ n: Number of candidate policies to sample.
+
+ Returns:
+ Tensor of indices into this module's children.
+ """
perm = torch.randperm(len(self._modules))
idx = perm[:n]
return idx
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
+ """Build a :class:`PolicySequential` for one RandAugment candidate op.
+
+ Args:
+ subpolicy: Single-entry policy as ``[(name, low, high)]``.
+
+ Returns:
+ Sequential wrapper around that operation.
+
+ Raises:
+ RuntimeError: ``subpolicy`` contains more than one operation.
+ """
if len(subpolicy) != 1:
raise RuntimeError(f"Each policy must have only one operation for RandAugment. Got {len(subpolicy)}.")
name, low, high = subpolicy[0]
return PolicySequential(*[getattr(ops, name)(low, high)])
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ """Return the policy modules to execute for this forward call.
+
+ Args:
+ params: Optional recorded parameters. When provided, the sequence is
+ reconstructed from them.
+
+ Returns:
+ Iterator of ``(name, module)`` pairs.
+ """
if params is None:
- idx = self.rand_selector(
- self.n,
- )
+ idx = self.rand_selector(self.n)
return self.get_children_by_indices(idx)
return self.get_children_by_params(params)
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Sample parameters for the selected RandAugment operations.
+
+ Args:
+ batch_shape: Input shape used for parameter sampling.
+
+ Returns:
+ Parameters for the sampled operations, including magnitude scaled from
+ the global ``m`` value.
+ """
named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 7e8cc4dec..f280e79dd 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -79,12 +79,32 @@ class TrivialAugment(PolicyAugmentBase):
self.rand_selector = Categorical(selection_weights)
def compose_subpolicy_sequential(self, subpolicy: SUBPOLICY_CONFIG) -> PolicySequential:
+ """Build a :class:`PolicySequential` from one TrivialAugment candidate.
+
+ Args:
+ subpolicy: Single-entry policy as ``[(name, low, high)]``.
+
+ Returns:
+ Sequential wrapper around the selected operation.
+
+ Raises:
+ RuntimeError: ``subpolicy`` contains more than one operation.
+ """
if len(subpolicy) != 1:
raise RuntimeError(f"Each policy must have only one operation for TrivialAugment. Got {len(subpolicy)}.")
name, low, high = subpolicy[0]
return PolicySequential(*[getattr(ops, name)(low, high)])
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ """Return the operation sequence to execute.
+
+ Args:
+ params: Optional recorded parameters. When provided, the sequence is
+ reconstructed from them.
+
+ Returns:
+ Iterator of ``(name, module)`` pairs.
+ """
if params is None:
idx = self.rand_selector.sample((1,))
return self.get_children_by_indices(idx)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 4c9f0aea5..c421a267b 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -285,6 +285,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self.extra_args = extra_args or {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}}
def clear_state(self) -> None:
+ """Reset cached params and transformation-matrix state."""
self._reset_transform_matrix_state()
return super().clear_state()
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index faaa4610b..91182ec68 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -95,20 +95,52 @@ class BasicSequentialBase(nn.Sequential):
# TODO: Implement this for all submodules.
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Generate parameters for a forward pass.
+
+ Args:
+ batch_shape: Input batch shape.
+
+ Returns:
+ Per-module parameters in execution order.
+ """
raise NotImplementedError
def get_children_by_indices(self, indices: torch.Tensor) -> Iterator[Tuple[str, nn.Module]]:
+ """Yield child modules selected by index.
+
+ Args:
+ indices: Indices of children to fetch.
+
+ Yields:
+ ``(name, module)`` pairs matching ``indices`` order.
+ """
modules = list(self.named_children())
for idx in indices:
yield modules[idx]
def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, nn.Module]]:
+ """Yield child modules referenced by a list of params.
+
+ Args:
+ params: Parameter items whose ``name`` fields identify the children.
+
+ Yields:
+ ``(name, module)`` pairs matching ``params`` order.
+ """
modules = list(self.named_children())
# TODO: Wrong params passed here when nested ImageSequential
for param in params:
yield modules[list(dict(self.named_children()).keys()).index(param.name)]
def get_params_by_module(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> Iterator[ParamItem]:
+ """Create placeholder params for a module iterator.
+
+ Args:
+ named_modules: Modules that will be executed.
+
+ Yields:
+ :class:`ParamItem` entries with ``data=None``.
+ """
# This will not take module._params
for name, _ in named_modules:
yield ParamItem(name, None)
@@ -141,6 +173,13 @@ class SequentialBase(BasicSequentialBase):
return_transform: Optional[bool] = None,
keepdim: Optional[bool] = None,
) -> None:
+ """Propagate sequence-level flags to child augmentation modules.
+
+ Args:
+ same_on_batch: Override for ``same_on_batch``.
+ return_transform: Reserved for compatibility with older interfaces.
+ keepdim: Override for ``keepdim``.
+ """
for mod in self.children():
# MixAugmentation does not have return transform
if isinstance(mod, (_AugmentationBase, K.MixAugmentationBaseV2)):
@@ -153,6 +192,7 @@ class SequentialBase(BasicSequentialBase):
@property
def same_on_batch(self) -> Optional[bool]:
+ """Return the sequence-level ``same_on_batch`` setting."""
return self._same_on_batch
@same_on_batch.setter
@@ -162,6 +202,7 @@ class SequentialBase(BasicSequentialBase):
@property
def keepdim(self) -> Optional[bool]:
+ """Return the sequence-level ``keepdim`` setting."""
return self._keepdim
@keepdim.setter
@@ -212,6 +253,14 @@ class ImageSequentialBase(SequentialBase):
raise NotImplementedError
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Generate parameters for child modules.
+
+ Args:
+ batch_shape: Input batch shape.
+
+ Returns:
+ Per-module parameter list.
+ """
raise NotImplementedError
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
@@ -221,6 +270,16 @@ class ImageSequentialBase(SequentialBase):
def transform_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply the sequence to an input tensor.
+
+ Args:
+ input: Input tensor.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed tensor.
+ """
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
@@ -229,6 +288,16 @@ class ImageSequentialBase(SequentialBase):
def inverse_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply inverse transforms for an input tensor.
+
+ Args:
+ input: Tensor produced by :meth:`transform_inputs`.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Tensor mapped back through inverse operations.
+ """
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
@@ -236,6 +305,16 @@ class ImageSequentialBase(SequentialBase):
def transform_masks(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply the sequence to mask tensors.
+
+ Args:
+ input: Mask tensor.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed mask tensor.
+ """
for param in params:
module = self.get_submodule(param.name)
input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
@@ -244,6 +323,16 @@ class ImageSequentialBase(SequentialBase):
def inverse_masks(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply inverse transforms for mask tensors.
+
+ Args:
+ input: Mask tensor produced by :meth:`transform_masks`.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Inverse-transformed mask tensor.
+ """
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
@@ -251,6 +340,16 @@ class ImageSequentialBase(SequentialBase):
def transform_boxes(
self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
+ """Apply the sequence to bounding boxes.
+
+ Args:
+ input: Bounding boxes.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed boxes.
+ """
for param in params:
module = self.get_submodule(param.name)
input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
@@ -259,6 +358,16 @@ class ImageSequentialBase(SequentialBase):
def inverse_boxes(
self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
+ """Apply inverse transforms for bounding boxes.
+
+ Args:
+ input: Boxes produced by :meth:`transform_boxes`.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Inverse-transformed boxes.
+ """
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
@@ -266,6 +375,16 @@ class ImageSequentialBase(SequentialBase):
def transform_keypoints(
self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
+ """Apply the sequence to keypoints.
+
+ Args:
+ input: Keypoints.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed keypoints.
+ """
for param in params:
module = self.get_submodule(param.name)
input = KeypointSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
@@ -274,6 +393,18 @@ class ImageSequentialBase(SequentialBase):
def inverse_keypoints(
self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
+ """Apply inverse transforms for keypoints.
+
+ Args:
+ input: Keypoints produced by :meth:`transform_keypoints` (conceptually
+ ``(B, N, 2)`` coordinates, where the last dimension stores
+ ``(x, y)``.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Inverse-transformed keypoints.
+ """
for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
@@ -301,6 +432,17 @@ class ImageSequentialBase(SequentialBase):
def forward(
self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Run the sequential augmentation pipeline.
+
+ Args:
+ input: Input tensor.
+ params: Optional precomputed parameters. If omitted, parameters are
+ sampled from ``input``.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Augmented tensor.
+ """
self.clear_state()
if params is None:
diff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.py
index b98089aec..72787a6e9 100644
--- a/kornia/augmentation/container/dispatcher.py
+++ b/kornia/augmentation/container/dispatcher.py
@@ -60,6 +60,14 @@ class ManyToManyAugmentationDispather(nn.Module):
return True
def forward(self, *input: Union[List[Tensor], List[Tuple[Tensor]]]) -> Union[List[Tensor], List[Tuple[Tensor]]]:
+ """Apply each augmentation to the matching input tuple.
+
+ Args:
+ *input: One input bundle per configured augmentation.
+
+ Returns:
+ Outputs from each augmentation, preserving input order.
+ """
return [aug(*inp) for inp, aug in zip(input, self.augmentations)]
@@ -111,4 +119,12 @@ class ManyToOneAugmentationDispather(nn.Module):
return True
def forward(self, *input: Union[Tensor, Tuple[Tensor]]) -> Union[List[Tensor], List[Tuple[Tensor]]]:
+ """Apply all augmentations to the same input payload.
+
+ Args:
+ *input: Shared input payload passed to every augmentation.
+
+ Returns:
+ One output per augmentation sequence.
+ """
return [aug(*input) for aug in self.augmentations]
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 0341ac867..0d61436f9 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -224,6 +224,19 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, K.MixAugmentationBaseV2)]
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ """Return the module sequence used for the current forward call.
+
+ Args:
+ params: Optional recorded parameters. When provided, the sequence is
+ reconstructed from them.
+
+ Returns:
+ Iterator of ``(name, module)`` pairs.
+
+ Raises:
+ ValueError: More than one mix augmentation is present while
+ ``random_apply`` is disabled.
+ """
if params is None:
# Mix augmentation can only be applied once per forward
mix_indices = self.get_mix_augmentation_indices(self.named_children())
@@ -242,6 +255,14 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
return self.get_children_by_params(params)
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Generate parameters for all modules in the chosen sequence.
+
+ Args:
+ batch_shape: Input batch shape.
+
+ Returns:
+ Parameter list aligned with the execution order.
+ """
named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 814ff4c9c..31d3eab63 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -44,6 +44,17 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
def get_instance_module_param(cls, param: ParamItem) -> Dict[str, torch.Tensor]:
+ """Extract per-module parameter dict from a :class:`ParamItem`.
+
+ Args:
+ param: Parameter wrapper produced by sequential containers.
+
+ Returns:
+ Dictionary of tensor parameters for one module call.
+
+ Raises:
+ TypeError: ``param.data`` is not a dictionary.
+ """
if isinstance(param, ParamItem) and isinstance(param.data, dict):
_params = param.data
else:
@@ -52,6 +63,17 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
def get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]:
+ """Extract nested sequential parameters from a :class:`ParamItem`.
+
+ Args:
+ param: Parameter wrapper produced by sequential containers.
+
+ Returns:
+ List of :class:`ParamItem` values for nested modules.
+
+ Raises:
+ TypeError: ``param.data`` is not a list.
+ """
if isinstance(param, ParamItem) and isinstance(param.data, list):
_params = param.data
else:
@@ -102,6 +124,7 @@ class AugmentationSequentialOps:
@property
def data_keys(self) -> Optional[List[DataKey]]:
+ """Return currently configured data keys."""
return self._data_keys
@data_keys.setter
@@ -112,6 +135,18 @@ class AugmentationSequentialOps:
self._data_keys = None
def preproc_datakeys(self, data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None) -> List[DataKey]:
+ """Normalize user-provided data keys into :class:`DataKey` values.
+
+ Args:
+ data_keys: Optional keys passed by the caller. If omitted, this method
+ uses ``self.data_keys``.
+
+ Returns:
+ Normalized list of data keys.
+
+ Raises:
+ ValueError: Neither argument nor instance-level keys are available.
+ """
if data_keys is None:
if isinstance(self.data_keys, list):
return self.data_keys
@@ -141,6 +176,19 @@ class AugmentationSequentialOps:
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, SequenceDataType]:
+ """Apply one module to all inputs according to their data keys.
+
+ Args:
+ *arg: Inputs to transform (image, mask, boxes, keypoints, ...).
+ module: Module to execute.
+ param: Parameters associated with ``module``.
+ extra_args: Optional runtime overrides keyed by :class:`DataKey`.
+ data_keys: Optional key override for this call.
+
+ Returns:
+ Transformed output(s). A single value is returned for one input,
+ otherwise a list is returned.
+ """
_data_keys = self.preproc_datakeys(data_keys)
if isinstance(module, K.RandomTransplantation):
@@ -175,6 +223,19 @@ class AugmentationSequentialOps:
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, SequenceDataType]:
+ """Apply inverse transformation dispatch for one module step.
+
+ Args:
+ *arg: Inputs to invert.
+ module: Module used in the forward pass.
+ param: Parameters captured for ``module`` during forward.
+ extra_args: Optional runtime overrides keyed by :class:`DataKey`.
+ data_keys: Optional key override for this call.
+
+ Returns:
+ Inverse-transformed output(s). A single value is returned for one
+ input, otherwise a list is returned.
+ """
_data_keys = self.preproc_datakeys(data_keys)
outputs = []
for inp, dcate in zip(arg, _data_keys):
@@ -220,6 +281,20 @@ class InputSequentialOps(SequentialOpsInterface[torch.Tensor]):
def transform(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply one module step to an image tensor.
+
+ Args:
+ input: Input image tensor.
+ module: Module to execute.
+ param: Parameters for ``module``.
+ extra_args: Optional runtime overrides.
+
+ Returns:
+ Transformed tensor.
+
+ Raises:
+ AssertionError: A non-augmentation module receives non-empty params.
+ """
if extra_args is None:
extra_args = {}
if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
@@ -238,6 +313,20 @@ class InputSequentialOps(SequentialOpsInterface[torch.Tensor]):
def inverse(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply one inverse module step to an image tensor.
+
+ Args:
+ input: Tensor to invert.
+ module: Module used in the forward path.
+ param: Forward parameters for ``module``.
+ extra_args: Optional runtime overrides.
+
+ Returns:
+ Inverse-transformed tensor.
+
+ Raises:
+ NotImplementedError: Inverse for 3D geometric ops is not supported.
+ """
if extra_args is None:
extra_args = {}
if isinstance(module, K.GeometricAugmentationBase2D):
@@ -262,6 +351,20 @@ class ClassSequentialOps(SequentialOpsInterface[torch.Tensor]):
def transform(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply class-label handling for one module step.
+
+ Args:
+ input: Class-label tensor.
+ module: Module to execute.
+ param: Parameters for ``module``.
+ extra_args: Optional runtime overrides.
+
+ Returns:
+ Class labels after transformation handling.
+
+ Raises:
+ NotImplementedError: Label-changing mix ops are not supported yet.
+ """
if isinstance(module, K.MixAugmentationBaseV2):
raise NotImplementedError(
"The support for class labels for mix augmentations that change the class label is not yet supported."
@@ -272,6 +375,20 @@ class ClassSequentialOps(SequentialOpsInterface[torch.Tensor]):
def inverse(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Return class labels unchanged during inverse dispatch.
+
+ Note:
+ Class labels do not have a geometric inverse in this pipeline.
+
+ Args:
+ input: Class-label tensor.
+ module: Module used in forward (unused).
+ param: Forward parameters (unused).
+ extra_args: Optional runtime overrides (unused).
+
+ Returns:
+ Unmodified class labels.
+ """
return input
@@ -591,11 +708,15 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input torch.Tensor.
+ input: Input keypoints. Coordinates are conceptually stored as
+ ``(B, N, 2)``, where the last dimension stores ``(x, y)``.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
+
+ Returns:
+ Keypoints after inverse transformation.
"""
if extra_args is None:
extra_args = {}
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 7a5403739..f8be7684e 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -172,6 +172,19 @@ class PatchSequential(ImageSequential):
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)``.
+
+ Raises:
+ NotImplementedError: ``padding`` is neither ``"same"`` nor ``"valid"``.
+ """
if grid_size is None:
grid_size = self.grid_size
if padding == "valid":
@@ -260,6 +273,15 @@ class PatchSequential(ImageSequential):
return restored_tensor
def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override]
+ """Generate patch-level parameters for a forward pass.
+
+ Args:
+ batch_shape: Shape of the extracted patch batch.
+
+ Returns:
+ List of :class:`PatchParamItem` entries, including patch indices and
+ operation params.
+ """
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:]]))
@@ -322,6 +344,15 @@ class PatchSequential(ImageSequential):
yield ParamItem(s[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:])
@@ -337,6 +368,16 @@ class PatchSequential(ImageSequential):
def transform_inputs( # type: ignore[override]
self, input: torch.Tensor, params: 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`.
+ 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)
input = self.forward_by_params(input, params)
@@ -347,6 +388,19 @@ class PatchSequential(ImageSequential):
def inverse_inputs( # type: ignore[override]
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
@@ -355,6 +409,19 @@ class PatchSequential(ImageSequential):
def transform_masks( # type: ignore[override]
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
@@ -363,6 +430,19 @@ class PatchSequential(ImageSequential):
def inverse_masks( # type: ignore[override]
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
@@ -371,6 +451,19 @@ class PatchSequential(ImageSequential):
def transform_boxes( # type: ignore[override]
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
@@ -379,6 +472,19 @@ class PatchSequential(ImageSequential):
def inverse_boxes( # type: ignore[override]
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
@@ -387,6 +493,19 @@ class PatchSequential(ImageSequential):
def transform_keypoints( # type: ignore[override]
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
@@ -395,6 +514,20 @@ class PatchSequential(ImageSequential):
def inverse_keypoints( # type: ignore[override]
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
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 762801143..8baadc489 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -192,6 +192,15 @@ class VideoSequential(ImageSequential):
return input
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ """Generate per-module parameters for video inputs.
+
+ Args:
+ batch_shape: Video batch shape, typically 5D.
+
+ Returns:
+ Parameter list aligned with execution order, with values broadcast
+ across frames depending on ``same_on_frame`` and module settings.
+ """
frame_num = batch_shape[self._temporal_channel]
named_modules = self.get_forward_sequence()
# Got param generation shape to (B, C, H, W). Ignoring T.
@@ -244,6 +253,16 @@ class VideoSequential(ImageSequential):
def transform_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply sequence transforms to video tensors.
+
+ Args:
+ input: Input video tensor.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed video tensor in the original video layout.
+ """
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -255,6 +274,16 @@ class VideoSequential(ImageSequential):
def inverse_inputs(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply inverse sequence transforms to video tensors.
+
+ Args:
+ input: Augmented video tensor.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Inverse-transformed video tensor in the original layout.
+ """
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -266,6 +295,16 @@ class VideoSequential(ImageSequential):
def transform_masks(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply sequence transforms to video mask tensors.
+
+ Args:
+ input: Input video mask tensor.
+ params: Parameters aligned with the execution sequence.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Transformed mask tensor in the original video layout.
+ """
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -277,6 +316,16 @@ class VideoSequential(ImageSequential):
def inverse_masks(
self, input: torch.Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
+ """Apply inverse sequence transforms to video masks.
+
+ Args:
+ input: Augmented video mask tensor.
+ params: Parameters used during forward execution.
+ extra_args: Optional per-input-type overrides.
+
+ Returns:
+ Inverse-transformed mask tensor in the original layout.
+ """
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.py
index e9ac0644d..8aa73d038 100644
--- a/kornia/augmentation/presets/ada.py
+++ b/kornia/augmentation/presets/ada.py
@@ -169,6 +169,16 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
ratio: Union[torch.Tensor, Tuple[float, float]],
value: float,
) -> Tuple[Union[_AugmentationBase, ImageSequential], ...]:
+ """Return the default augmentation stack used by ADA.
+
+ Args:
+ scale: Erase-area range passed to :class:`RandomErasing`.
+ ratio: Erase-aspect-ratio range passed to :class:`RandomErasing`.
+ value: Fill value used by :class:`RandomErasing`.
+
+ Returns:
+ Tuple of augmentation modules applied inside ADA.
+ """
# if changed in the future, please change the expected transforms list in test_presets.py
return (
RandomHorizontalFlip(p=1),
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 7fcda8f07..ad230c880 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -67,14 +67,45 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
# TODO: refine the logic with module.to()
def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase":
+ """Update sampler device and dtype using ``torch.nn.Module.to`` semantics.
+
+ Args:
+ *args: Positional arguments accepted by ``Module.to``.
+ **kwargs: Keyword arguments accepted by ``Module.to``.
+
+ Returns:
+ This generator instance.
+ """
device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs)
self.set_rng_device_and_dtype(device=device, dtype=dtype)
return self
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ """Create distribution samplers for the given device and dtype.
+
+ Args:
+ device: Target device.
+ dtype: Target floating-point dtype.
+
+ Raises:
+ NotImplementedError: Subclass did not implement sampler creation.
+ """
raise NotImplementedError
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ """Sample random augmentation parameters.
+
+ Args:
+ batch_shape: Target batch shape.
+ same_on_batch: If ``True``, use one sample and broadcast it across the
+ batch dimension.
+
+ Returns:
+ Dictionary of tensors consumed by augmentation modules.
+
+ Raises:
+ NotImplementedError: Subclass did not implement parameter sampling.
+ """
raise NotImplementedError
@@ -109,18 +140,42 @@ class DistributionWithMapper(Distribution):
self.map_fn = map_fn
def rsample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
+ """Draw a reparameterized sample and apply ``map_fn`` when provided.
+
+ Args:
+ sample_shape: Desired sample shape.
+
+ Returns:
+ Sample tensor after optional mapping.
+ """
out = self.dist.rsample(torch.Size(sample_shape))
if self.map_fn is not None:
out = self.map_fn(out)
return out
def sample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
+ """Draw a sample and apply ``map_fn`` when provided.
+
+ Args:
+ sample_shape: Desired sample shape.
+
+ Returns:
+ Sample tensor after optional mapping.
+ """
out = self.dist.sample(torch.Size(sample_shape))
if self.map_fn is not None:
out = self.map_fn(out)
return out
def sample_n(self, n: int) -> torch.Tensor:
+ """Draw ``n`` samples and apply ``map_fn`` when provided.
+
+ Args:
+ n: Number of samples.
+
+ Returns:
+ Sample tensor after optional mapping.
+ """
out = self.dist.sample_n(n)
if self.map_fn is not None:
out = self.map_fn(out)