Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(augmentation): CUDA augmentations move their parameters without host synchronization (#6084)

Dmytro Mishkind0415e664873
diff --git a/changelog.d/6084.fixed.md b/changelog.d/6084.fixed.md
new file mode 100644
index 000000000..e434d6895
--- /dev/null
+++ b/changelog.d/6084.fixed.md
@@ -0,0 +1,11 @@
+Augmentations no longer synchronize with the GPU to move their parameters in eager mode: parameters sampled on the CPU
+and per-call constants reach CUDA inputs without a `cudaStreamSynchronize`, in every 2D, 3D, mix, container and
+automatic-policy augmentation, in `forward` and `inverse`, and with mask, box, keypoint and class inputs. Values are
+unchanged bit for bit, and compiled graphs keep their copies. The synchronizations that remain are the ones whose
+result the host needs: `inverse()` and the 3D warps invert the transformation matrix with `torch.linalg.inv`, which
+raises for a singular matrix; `RandomThinPlateSpline` solves its spline system with `torch.linalg.solve` for the same
+reason; box inputs are validated (now in one host read instead of three); and
+`RandomTransplantation` and `AdaptiveDiscriminatorAugmentation` draw from data on the device. Parameters as large as
+the image (noise, plasma and illumination maps, elastic noise, salt-and-pepper masks) still cost the host the time of a
+pageable copy, and an augmentation moved to the GPU with `.to("cuda")` samples its parameters on the GPU and still
+reads them back.
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index ee764443a..d1fe70804 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -25,7 +25,7 @@ from torch import float16, float32, float64
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
from kornia.core.ops import eye_like
-from kornia.core.utils import is_autocast_enabled, is_compiling, is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_compiling, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -261,8 +261,8 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
# If batch sizes line up, do the where-blend. Otherwise (e.g. VideoSequential
# passes B-sized batch_prob into a B*T-sized input) fall back to all-or-nothing.
if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:
- to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))).to(
- trans_matrix_applied.device
+ to_apply_expanded = _to_device_nonblocking(
+ to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))), trans_matrix_applied.device
)
trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)
else:
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index dbfed57be..b7ec0ef62 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
+from kornia.core.utils import _as_tensor_nonblocking
from kornia.geometry.transform import get_affine_matrix2d, warp_affine
@@ -142,13 +143,13 @@ class RandomAffine(GeometricAugmentationBase2D):
# does not support at opset 20. Multiply by ``pi/180`` explicitly same value,
# but only basic arithmetic ops in the trace.
deg2rad_factor: float = math.pi / 180.0
- shear_x = torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype) * deg2rad_factor
- shear_y = torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype) * deg2rad_factor
+ shear_x = _as_tensor_nonblocking(params["shear_x"], input.device, input.dtype) * deg2rad_factor
+ shear_y = _as_tensor_nonblocking(params["shear_y"], input.device, input.dtype) * deg2rad_factor
return get_affine_matrix2d(
- torch.as_tensor(params["translations"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["scale"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["angle"], device=input.device, dtype=input.dtype),
+ _as_tensor_nonblocking(params["translations"], input.device, input.dtype),
+ _as_tensor_nonblocking(params["center"], input.device, input.dtype),
+ _as_tensor_nonblocking(params["scale"], input.device, input.dtype),
+ _as_tensor_nonblocking(params["angle"], input.device, input.dtype),
shear_x,
shear_y,
)
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 23ea526e0..f06c5af01 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import crop_by_transform_mat
from kornia.geometry.transform.crop2d import _crop_inverse_by_transform_mat, _crop_translation
@@ -125,7 +126,9 @@ class CenterCrop(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
- transform = _crop_translation(params["src"].to(input), params["dst"].to(input))
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ transform = _crop_translation(src, dst)
return transform.expand(input.shape[0], -1, -1)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 806f31146..b9051826c 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -26,7 +26,7 @@ from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.augmentation.base import _mixed_gate_shape_error
from kornia.augmentation.utils.helpers import _constant_tensor, _pad_with_fill
from kornia.constants import Resample
-from kornia.core.utils import is_compiling, is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_compiling, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat
@@ -223,7 +223,7 @@ class RandomCrop(GeometricAugmentationBase2D):
if is_exporting() or not isinstance(padding, torch.Tensor):
# Recompute the canvas from the module flags, as ``precrop_padding`` does for the pixels.
padding = _constant_tensor(tuple(self.compute_padding(tuple(input.shape))), dtype=torch.long)[None]
- return padding[:, ::2].to(input)
+ return _to_device_nonblocking(padding[:, ::2], input.device, input.dtype)
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
@@ -238,8 +238,8 @@ class RandomCrop(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
if flags["cropping_mode"] in ("resample", "slice"):
- src = params["src"].to(input)
- dst = params["dst"].to(input)
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
transform = _crop_translation(src, dst)
# Scale against the canvas represented by the effective replay parameters.
@@ -264,12 +264,12 @@ class RandomCrop(GeometricAugmentationBase2D):
transform[:, 1, 1] *= h_out / h
return transform
- padding_size = padding_size.to(device=input.device)
+ padding_size = _to_device_nonblocking(padding_size, input.device)
canvas = params.get("forward_input_shape")
if isinstance(canvas, torch.Tensor) and input.shape[0] > 0:
# The recorded padded canvas: an inverse passes the crop output as ``input``, and its shape would
# lose the scale of an oversized crop. A forward call records the canvas it is given, so it agrees.
- canvas = canvas.to(device=input.device)
+ canvas = _to_device_nonblocking(canvas, input.device)
padded_h = canvas[-2].expand(input.shape[0])
padded_w = canvas[-1].expand(input.shape[0])
else:
@@ -337,7 +337,9 @@ class RandomCrop(GeometricAugmentationBase2D):
offset = self._padding_offset(input, params).to(transform)
if not (self.p == 1.0 and self.p_batch == 1.0):
# Only selected matrices include padding. Keep skipped rows as identity.
- applied = torch.atleast_1d(params["batch_prob"] > 0.5).to(offset)
+ applied = _to_device_nonblocking(
+ torch.atleast_1d(params["batch_prob"] > 0.5), offset.device, offset.dtype
+ )
applied = applied if applied.shape[0] == transform.shape[0] else applied.any()
offset = offset * applied.reshape(-1, 1)
transform = transform.clone()
@@ -413,7 +415,9 @@ class RandomCrop(GeometricAugmentationBase2D):
# The inverse matrix returns original coordinates. The image inverse still renders
# onto forward_input_shape (the padded canvas), then removes its border below.
transform = transform.clone()
- transform[:, :2, 2] += params["padding_size"][:, ::2].to(transform)
+ transform[:, :2, 2] += _to_device_nonblocking(
+ params["padding_size"][:, ::2], transform.device, transform.dtype
+ )
to_apply = self._gate(params)
if not to_apply.any():
return super().inverse_inputs(input, params, flags, transform, **kwargs)
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index de83f246b..b6061a7ef 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import elastic_transform2d
@@ -112,7 +113,7 @@ class RandomElasticTransform(AugmentationBase2D):
) -> torch.Tensor:
return elastic_transform2d(
input,
- params["noise"].to(input),
+ _to_device_nonblocking(params["noise"], input.device, input.dtype),
flags["kernel_size"],
flags["sigma"],
flags["alpha"],
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index aad218235..551c61056 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.grid import create_meshgrid
from kornia.geometry.transform import remap
@@ -102,12 +103,12 @@ class RandomFisheye(AugmentationBase2D):
# create the initial sampling fields
B, _, H, W = input.shape
grid = create_meshgrid(H, W, normalized_coordinates=True)
- field_x = grid[..., 0].to(input) # 1xHxW
- field_y = grid[..., 1].to(input) # 1xHxW
+ field_x = _to_device_nonblocking(grid[..., 0], input.device, input.dtype) # 1xHxW
+ field_y = _to_device_nonblocking(grid[..., 1], input.device, input.dtype) # 1xHxW
# vectorize the random parameters
- center_x = params["center_x"].view(B, 1, 1).to(input)
- center_y = params["center_y"].view(B, 1, 1).to(input)
- gamma = params["gamma"].view(B, 1, 1).to(input)
+ center_x = _to_device_nonblocking(params["center_x"].view(B, 1, 1), input.device, input.dtype)
+ center_y = _to_device_nonblocking(params["center_y"].view(B, 1, 1), input.device, input.dtype)
+ gamma = _to_device_nonblocking(params["gamma"].view(B, 1, 1), input.device, input.dtype)
# compute and apply the distances respect to the camera optical center
distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
field_x = field_x + field_x * distance**gamma # BxHxw
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 8ed8b31f5..a63a36370 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -22,6 +22,8 @@ import torch
# from torch import Tensor (use torch.Tensor instead)
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import hflip
@@ -87,13 +89,12 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- # Build the 3x3 flip matrix as a constant literal plus the (tensor) width, rather than
- # `int(w)`. `int(tensor)` lowers to `.item()`, which breaks torch.compile fullgraph on
- # some torch versions; a Python-float literal is fine (constant-folded) and adding the
- # width tensor into entry [0, 2] gives `w - 1` β€” numerically identical to
- # `[[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]]`, and ~1.8x cheaper than stacking 9 scalars.
- w = params["forward_input_shape"][-1].to(device=input.device, dtype=input.dtype)
- flip_mat: torch.Tensor = torch.tensor(
+ # Build the 3x3 flip matrix as a literal filled on the device plus the (tensor) width, rather than
+ # `int(w)`, which lowers to `.item()` and breaks torch.compile fullgraph, or a `torch.tensor` literal,
+ # which copies from the host and waits for the queued kernels. Entry [0, 2] becomes `-1 + w` in the input
+ # dtype, as before.
+ w = _to_device_nonblocking(params["forward_input_shape"][-1], input.device, input.dtype)
+ flip_mat: torch.Tensor = _device_literal(
[[-1.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=input.device, dtype=input.dtype
)
flip_mat[0, 2] = flip_mat[0, 2] + w
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 07a133b46..38cd93f06 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import get_perspective_transform, warp_perspective
@@ -104,7 +105,9 @@ class RandomPerspective(GeometricAugmentationBase2D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
+ start_points = _to_device_nonblocking(params["start_points"], input.device, input.dtype)
+ end_points = _to_device_nonblocking(params["end_points"], input.device, input.dtype)
+ return get_perspective_transform(start_points, end_points)
def apply_transform(
self,
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 91db3ac20..543668dd6 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -23,7 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core.utils import is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_exporting
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
from kornia.geometry.transform._crop import _half_pixel_resize_transform
from kornia.geometry.transform.affwarp import _side_to_image_size
@@ -90,17 +90,17 @@ class Resize(GeometricAugmentationBase2D):
if flags["resample"] == Resample.NEAREST or (
not flags["align_corners"] and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC)
):
- return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(
- input.shape[0], -1, -1
- )
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ return _half_pixel_resize_transform(src, dst).expand(input.shape[0], -1, -1)
# NOTE: a former `if params["output_size"] == input.shape[-2:]: return eye_like(...)`
# short-circuit was dead code β€” comparing a tensor to a ``torch.Size`` falls back to
# identity ``==`` and is *always* Python ``False``, so the branch never ran. It also
# graph-broke torch.compile (a Python ``if`` on a would-be tensor). Dropped; the
# perspective transform below already yields identity when src == dst, so behaviour is
# byte-identical.
- transform: torch.Tensor = torch.as_tensor(
- get_perspective_transform(params["src"], params["dst"]), dtype=input.dtype, device=input.device
+ transform: torch.Tensor = _to_device_nonblocking(
+ get_perspective_transform(params["src"], params["dst"]), input.device, input.dtype
)
return transform.expand(input.shape[0], -1, -1)
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 3002cf16e..b74e882c1 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -25,7 +25,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core.utils import is_compiling
+from kornia.core.utils import _to_device_nonblocking, is_compiling
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
from kornia.geometry.transform._crop import (
_compiled_slice_resize,
@@ -41,7 +41,7 @@ def _one_pixel_axes(box: torch.Tensor, device: torch.device) -> torch.Tensor:
Read from the box in its stored dtype: cast to a half-precision input's dtype first, neighbouring coordinates
above 256 can round to one value in bfloat16 and make a two-pixel box look one pixel wide.
"""
- box = box.to(device)
+ box = _to_device_nonblocking(box, device)
return (box[:, 2] - box[:, 0]) == 0
@@ -165,11 +165,12 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
flags["resample"] == Resample.NEAREST
or (not flags["align_corners"] and flags["resample"] in (Resample.BILINEAR, Resample.BICUBIC))
):
- return _half_pixel_resize_transform(params["src"].to(input), params["dst"].to(input)).expand(
- input.shape[0], -1, -1
- )
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ return _half_pixel_resize_transform(src, dst).expand(input.shape[0], -1, -1)
if flags["cropping_mode"] in ("resample", "slice"):
- src, dst = params["src"].to(input), params["dst"].to(input)
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
transform: torch.Tensor = get_perspective_transform(src, dst)
# A one-pixel crop or output axis makes the box vertices collinear, and the solve returns NaN or a
# singular matrix. Corner-aligned resizing samples the crop's first pixel along that axis, which the
@@ -233,9 +234,10 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
# onto the canvas pixels after it. With zero padding, everything outside the crop is zero.
if kwargs.get("padding_mode", flags["padding_mode"]) != "zeros" or output.shape[0] == 0:
return output
- one_pixel = _one_pixel_axes(params["src"], output.device) & self._gate(params).to(output.device)[:, None]
+ gate = _to_device_nonblocking(self._gate(params), output.device)
+ one_pixel = _one_pixel_axes(params["src"], output.device) & gate[:, None]
# Integer pixel indices: in bfloat16 neighbouring indices above 256 round to the same value.
- start = params["src"][:, 0].to(output.device).round().long()
+ start = _to_device_nonblocking(params["src"][:, 0], output.device).round().long()
columns = torch.arange(output.shape[-1], device=output.device)
rows = torch.arange(output.shape[-2], device=output.device)
keep_columns = ~one_pixel[:, :1] | (columns == start[:, :1])
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 5f7dc3658..87fbb8c50 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -23,6 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
from kornia.core.ops import eye_like
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import affine
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
@@ -102,7 +103,7 @@ class RandomRotation(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
# TODO: Update to use `get_rotation_matrix2d`
- angles: torch.Tensor = params["degrees"].to(input)
+ angles: torch.Tensor = _to_device_nonblocking(params["degrees"], input.device, input.dtype)
center: torch.Tensor = _compute_tensor_center(input)
rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
@@ -214,7 +215,7 @@ class RandomRotation90(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: dict[str, torch.Tensor], flags: dict[str, Any]
) -> torch.Tensor:
# TODO: Update to use `get_rotation_matrix2d`
- angles: torch.Tensor = 90.0 * params["times"].round().to(input)
+ angles: torch.Tensor = 90.0 * _to_device_nonblocking(params["times"].round(), input.device, input.dtype)
center: torch.Tensor = _compute_tensor_center(input)
rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 53bfd8d29..be0e194b5 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
+from kornia.core.utils import _as_tensor_nonblocking
# from kornia.geometry.conversions import deg2rad (use torch.deg2rad instead)
from kornia.geometry.transform import get_shear_matrix2d, warp_affine
@@ -107,10 +108,10 @@ class RandomShear(GeometricAugmentationBase2D):
# Inline ``deg2rad`` so the trace lowers to plain multiply (legacy ONNX has
# no symbolic for ``aten::deg2rad`` at opset 20).
deg2rad_factor: float = math.pi / 180.0
- shear_x = torch.as_tensor(params["shear_x"], device=input.device, dtype=input.dtype) * deg2rad_factor
- shear_y = torch.as_tensor(params["shear_y"], device=input.device, dtype=input.dtype) * deg2rad_factor
+ shear_x = _as_tensor_nonblocking(params["shear_x"], input.device, input.dtype) * deg2rad_factor
+ shear_y = _as_tensor_nonblocking(params["shear_y"], input.device, input.dtype) * deg2rad_factor
return get_shear_matrix2d(
- torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ _as_tensor_nonblocking(params["center"], input.device, input.dtype),
shear_x,
shear_y,
)
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index c3e27ceb1..d21f06b94 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.constants import SamplePadding
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import get_tps_transform, warp_image_tps
@@ -116,8 +117,8 @@ class RandomThinPlateSpline(AugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- src = params["src"].to(input)
- dst = params["dst"].to(input)
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
# NOTE: warp_image_tps need to use inverse parameters
kernel, affine = get_tps_transform(dst, src)
return warp_image_tps(input, src, kernel, affine, flags["align_corners"], flags["padding_mode"].name.lower())
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index a143f827d..9e59ae1e2 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
+from kornia.core.utils import _as_tensor_nonblocking
from kornia.geometry.transform import get_translation_matrix2d, warp_affine
@@ -102,7 +103,7 @@ class RandomTranslate(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
translations = torch.stack([params["translate_x"], params["translate_y"]], dim=-1)
- return get_translation_matrix2d(torch.as_tensor(translations, device=input.device, dtype=input.dtype))
+ return get_translation_matrix2d(_as_tensor_nonblocking(translations, input.device, input.dtype))
def apply_transform(
self,
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 1a802f349..3fdf9723f 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -21,6 +21,8 @@ import torch
from kornia.augmentation._2d.base import _input_metadata_only
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import vflip
@@ -78,13 +80,12 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- # Build the 3x3 flip matrix as a constant literal plus the (tensor) height, rather than
- # `int(h)`. `int(tensor)` lowers to `.item()`, which breaks torch.compile fullgraph on
- # some torch versions; a Python-float literal is fine (constant-folded) and adding the
- # height tensor into entry [1, 2] gives `h - 1` β€” numerically identical to
- # `[[1, 0, 0], [0, -1, h - 1], [0, 0, 1]]`, and ~1.8x cheaper than stacking 9 scalars.
- h = params["forward_input_shape"][-2].to(device=input.device, dtype=input.dtype)
- flip_mat: torch.Tensor = torch.tensor(
+ # Build the 3x3 flip matrix as a literal filled on the device plus the (tensor) height, rather than
+ # `int(h)`, which lowers to `.item()` and breaks torch.compile fullgraph, or a `torch.tensor` literal,
+ # which copies from the host and waits for the queued kernels. Entry [1, 2] becomes `-1 + h` in the input
+ # dtype, as before.
+ h = _to_device_nonblocking(params["forward_input_shape"][-2], input.device, input.dtype)
+ flip_mat: torch.Tensor = _device_literal(
[[1.0, 0.0, 0.0], [0.0, -1.0, -1.0], [0.0, 0.0, 1.0]], device=input.device, dtype=input.dtype
)
flip_mat[1, 2] = flip_mat[1, 2] + h
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index 24d38e2d2..c76e57812 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.augmentation.utils import _range_bound
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_brightness
@@ -109,5 +110,5 @@ class RandomBrightness(IntensityAugmentationBase2D):
) -> torch.Tensor:
if self.clip_output:
input = _clamp_unit_range(input)
- brightness_factor = params["brightness_factor"].to(input)
+ brightness_factor = _to_device_nonblocking(params["brightness_factor"], input.device, input.dtype)
return adjust_brightness(input, brightness_factor - 1, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index d526da99a..9981ac050 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import ChannelDropoutGenerator
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.core.utils import _to_device_nonblocking
class RandomChannelDropout(IntensityAugmentationBase2D):
@@ -131,8 +132,8 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
)
out = input.clone()
- out[params["batch_idx"], params["channel_idx"], ...] = self.fill_value.to(
- device=input.device, dtype=input.dtype
- )
+ batch_idx = _to_device_nonblocking(params["batch_idx"], input.device)
+ channel_idx = _to_device_nonblocking(params["channel_idx"], input.device)
+ out[batch_idx, channel_idx, ...] = _to_device_nonblocking(self.fill_value, input.device, input.dtype)
return out
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index de0186d5b..0cbcfec4f 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core.utils import _to_device_nonblocking
class RandomChannelShuffle(IntensityAugmentationBase2D):
@@ -77,4 +78,4 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
# a Python loop over the batch (which launched a kernel per sample and blocked
# torch.compile). `channels` is (B, C); indexing input[(B,1), (B,C)] gives (B, C, H, W).
batch_index = torch.arange(input.shape[0], device=input.device).view(-1, 1)
- return input[batch_index, params["channels"]]
+ return input[batch_index, _to_device_nonblocking(params["channels"], input.device)]
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 30d27959c..1fb5bc550 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation
@@ -60,11 +61,14 @@ def _apply_order_cond(
) -> torch.Tensor:
# Every step runs, and torch.where keeps its output only when a factor in the batch is not neutral. There is
# no data-dependent Python branch, so eager and compiled mode run this same code path, and fullgraph
- # compilation holds. A step runs even when it is skipped, so this path needs an RGB input.
+ # compilation holds. A step runs even when it is skipped, so this path needs an RGB input. The condition is
+ # computed from the CPU factors and moved without waiting for the queued kernels, as a CPU condition in
+ # ``torch.where`` would be copied with a blocking transfer.
for idx in order:
factor = factors[idx]
output = branches[idx](input, factor)
- input = torch.where((factor != neutral[idx]).any(), output, input)
+ apply = _to_device_nonblocking((factor != neutral[idx]).any(), input.device)
+ input = torch.where(apply, output, input)
return input
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 7a99fc2b8..55d1010b0 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.augmentation.utils import _range_bound
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_contrast
@@ -109,5 +110,5 @@ class RandomContrast(IntensityAugmentationBase2D):
) -> torch.Tensor:
if self.clip_output:
input = _clamp_unit_range(input)
- contrast_factor = params["contrast_factor"].to(input)
+ contrast_factor = _to_device_nonblocking(params["contrast_factor"], input.device, input.dtype)
return adjust_contrast(input, contrast_factor, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index fad867b58..cb213d244 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.bbox import bbox_generator, bbox_to_mask
@@ -113,7 +114,7 @@ class RandomErasing(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
_, _, h, w = input.size()
- values = params["values"].view(-1, 1, 1, 1).to(input)
+ values = _to_device_nonblocking(params["values"].view(-1, 1, 1, 1), input.device, input.dtype)
if self.same_on_batch:
# Every sample shares one rectangle, so write that single region directly instead of
@@ -136,7 +137,10 @@ class RandomErasing(IntensityAugmentationBase2D):
# `where` broadcasts to the input shape, so the result is identical while allocating two
# small tensors instead of two image-sized ones.
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
- mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input) # (B, 1, H, W)
+ # The (B, 4, 2) boxes cross to the device, not the (B, H, W) mask: a large pageable copy stalls the host while
+ # the driver stages it. The mask is 0 or 1 by exact comparisons, so it is the same on either device.
+ bboxes = _to_device_nonblocking(bboxes, input.device)
+ mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
return torch.where(mask == 1.0, values, input)
def apply_transform_mask(
@@ -154,5 +158,8 @@ class RandomErasing(IntensityAugmentationBase2D):
values = torch.zeros((), dtype=input.dtype, device=input.device)
bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
- mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input) # (B, 1, H, W)
+ # The (B, 4, 2) boxes cross to the device, not the (B, H, W) mask: a large pageable copy stalls the host while
+ # the driver stages it. The mask is 0 or 1 by exact comparisons, so it is the same on either device.
+ bboxes = _to_device_nonblocking(bboxes, input.device)
+ mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
return torch.where(mask == 1.0, values, input)
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index 01a5f9d28..93a8e843f 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_gamma
@@ -104,6 +105,6 @@ class RandomGamma(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
input = _clamp_unit_range(input)
- gamma_factor = params["gamma_factor"].to(input)
- gain_factor = params["gain_factor"].to(input)
+ gamma_factor = _to_device_nonblocking(params["gamma_factor"], input.device, input.dtype)
+ gain_factor = _to_device_nonblocking(params["gain_factor"], input.device, input.dtype)
return adjust_gamma(input, gamma_factor, gain_factor)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index db76585d9..483436d60 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -28,6 +28,7 @@ from kornia.augmentation._2d.intensity.base import (
)
from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerator
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
def _apply_gaussian_illumination(
@@ -39,7 +40,7 @@ def _apply_gaussian_illumination(
"""Apply a sampled illumination pattern through a picklable, compilable callable."""
# The gradient comes from the generator on CPU.
# We must explicitly move it to the input's device before adding.
- gradient = params["gradient"].to(input.device, input.dtype)
+ gradient = _to_device_nonblocking(params["gradient"], input.device, input.dtype)
# Out-of-place add: in-place would mutate the caller's tensor and corrupt
# the non-transformed branch, which shares the same input.
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index 96ab0e31b..668f92b0a 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core.utils import _to_device_nonblocking
class RandomGaussianNoise(IntensityAugmentationBase2D):
@@ -72,7 +73,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- gaussian_noise = params["gaussian_noise"].to(input)
+ gaussian_noise = _to_device_nonblocking(params["gaussian_noise"], input.device, input.dtype)
# When same_on_batch=True the generator produces shape (1, C, H, W); expand to full batch.
if gaussian_noise.shape[0] != input.shape[0]:
gaussian_noise = gaussian_noise.expand_as(input)
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
index 53c55a4ce..20518cdfa 100644
--- a/kornia/augmentation/_2d/intensity/grayscale.py
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -23,6 +23,7 @@ from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.color import rgb_to_grayscale
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
class RandomGrayscale(IntensityAugmentationBase2D):
@@ -114,7 +115,7 @@ class RandomGrayscale(IntensityAugmentationBase2D):
weights.numel() == num_channels,
lambda: f"rgb_weights needs one weight per channel: got {weights.numel()} for {num_channels}.",
)
- weights = weights.to(input)
+ weights = _to_device_nonblocking(weights, input.device, input.dtype)
gray = (input * weights.view(*lead, num_channels, 1, 1)).sum(-3, keepdim=True)
# Broadcast the single grayscale channel back to the input channel count (a contiguous copy).
return gray.repeat(*lead, num_channels, 1, 1)
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 5b75c011a..5e6ee92a3 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.augmentation.utils import _range_bound
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_hue
@@ -102,5 +103,5 @@ class RandomHue(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
input = _clamp_unit_range(input)
- hue_factor = params["hue_factor"].to(input)
+ hue_factor = _to_device_nonblocking(params["hue_factor"], input.device, input.dtype)
return _clamp_unit_range(adjust_hue(input, hue_factor * 2 * math.pi))
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
index fff5708dc..45a3299af 100644
--- a/kornia/augmentation/_2d/intensity/invert.py
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -21,6 +21,8 @@ import torch
from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance import invert
@@ -80,4 +82,10 @@ class RandomInvert(IntensityAugmentationBase2D):
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- return invert(input, torch.as_tensor(flags["max_val"], device=input.device, dtype=input.dtype))
+ max_val = flags["max_val"]
+ if isinstance(max_val, Tensor):
+ return invert(input, _to_device_nonblocking(max_val, input.device, input.dtype))
+ if isinstance(max_val, (int, float)):
+ # Filled on the device: ``torch.as_tensor(..., device=cuda)`` copies from the host and waits.
+ return invert(input, _device_literal(max_val, device=input.device, dtype=input.dtype))
+ return invert(input, torch.as_tensor(max_val, device=input.device, dtype=input.dtype))
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index 103d054ab..c2073b960 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGenerator
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
class RandomLinearIllumination(IntensityAugmentationBase2D):
@@ -141,7 +142,7 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
) -> torch.Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
input = _clamp_unit_range(input)
- return input.add(params["gradient"].to(input)).clamp(0, 1)
+ return input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)).clamp(0, 1)
class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
@@ -261,4 +262,4 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
) -> torch.Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
input = _clamp_unit_range(input)
- return input.add(params["gradient"].to(input)).clamp(0, 1)
+ return input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)).clamp(0, 1)
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index 4f931ff12..fa31430e2 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.utils import _to_device_nonblocking
def get_planckian_coeffs(mode: str) -> torch.Tensor:
@@ -209,7 +210,9 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"])
# Index with the tensor itself: `.tolist()` reads the data, which graph capture cannot do. Cast the
# buffer to the input so both device and dtype follow the input for the channel-wise multiplication.
- coeffs = self.pl.to(input)[params["idx"].long()]
+ coeffs = _to_device_nonblocking(self.pl, input.device, input.dtype)[
+ _to_device_nonblocking(params["idx"].long(), input.device)
+ ]
r_w = coeffs[:, 0][..., None, None]
b_w = coeffs[:, 1][..., None, None]
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index a1474cc38..d89cd5b8a 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.contrib import diamond_square
+from kornia.core.utils import _to_device_nonblocking
def _generate_plasma(
@@ -49,7 +50,7 @@ def _generate_plasma(
def _plasma_for_input(plasma: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
- return plasma[..., : image.shape[-2], : image.shape[-1]].to(image)
+ return _to_device_nonblocking(plasma[..., : image.shape[-2], : image.shape[-1]], image.device, image.dtype)
class RandomPlasmaBrightness(IntensityAugmentationBase2D):
@@ -119,7 +120,7 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
image = _clamp_unit_range(image)
- intensity = params["intensity"].to(image).view(-1, 1, 1, 1)
+ intensity = _to_device_nonblocking(params["intensity"], image.device, image.dtype).view(-1, 1, 1, 1)
brightness_map = 2 * _plasma_for_input(params["plasma"], image) - 1
brightness_map = brightness_map * intensity
return (image + brightness_map).clamp_(0, 1)
@@ -266,8 +267,8 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
image = _clamp_unit_range(image)
- shade_intensity = params["shade_intensity"].to(image).view(-1, 1, 1, 1)
- shade_quantity = params["shade_quantity"].to(image).view(-1, 1, 1, 1)
+ shade_intensity = _to_device_nonblocking(params["shade_intensity"], image.device, image.dtype).view(-1, 1, 1, 1)
+ shade_quantity = _to_device_nonblocking(params["shade_quantity"], image.device, image.dtype).view(-1, 1, 1, 1)
shade_map = _plasma_for_input(params["plasma"], image)
shade_map = (shade_map < shade_quantity).to(image.dtype) * shade_intensity
return (image + shade_map).clamp_(0, 1)
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index dbe7bb23f..68e5aa456 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -21,6 +21,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance import posterize
@@ -98,4 +99,4 @@ class RandomPosterize(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
input = _clamp_unit_range(input)
- return posterize(input, params["bits_factor"].to(input.device))
+ return posterize(input, _to_device_nonblocking(params["bits_factor"], input.device))
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index 5c044f7cc..2784a4e93 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -24,6 +24,7 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import RainGenerator
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
class RandomRain(IntensityAugmentationBase2D):
@@ -167,26 +168,29 @@ class RandomRain(IntensityAugmentationBase2D):
start_cols = torch.minimum((coordinates[..., 1] * cols_c).long(), cols_c - 1) + shift_c
# Two device copies for the whole batch: the host-built shapes and metadata as one flat
- # buffer, and the two start-coordinate grids as one stacked tensor.
+ # buffer, and the two start-coordinate grids as one stacked tensor. Both are built on the host, so they move
+ # without waiting for the queued kernels.
device = image.device
- host = torch.cat([lines.reshape(-1), meta.reshape(-1)]).to(device)
+ host = _to_device_nonblocking(torch.cat([lines.reshape(-1), meta.reshape(-1)]), device)
lines = host[: lines.numel()].view(batch_size, 2, longest_line)
meta = host[lines.numel() :].view(batch_size, 5)
- starts = torch.stack([start_rows, start_cols]).to(device)
+ starts = _to_device_nonblocking(torch.stack([start_rows, start_cols]), device)
# (B, max drops, longest line): every start offset by every step of its sample's line.
drop_rows = starts[0].unsqueeze(2) + lines[:, 0].unsqueeze(1)
drop_cols = starts[1].unsqueeze(2) + lines[:, 1].unsqueeze(1)
# Keep drop j of sample i only while j < its drawn drop count (the generator allocates the
- # batch maximum), and step k only while k < its line length (padding above). The mask is
- # resolved with a single `nonzero` (one device sync) and the batch index is recovered from
- # the flat position arithmetically, rather than boolean-indexing three tensors, which would
- # call `nonzero` three times.
+ # batch maximum), and step k only while k < its line length (padding above).
drop_valid = torch.arange(max_drops, device=device).unsqueeze(0) < meta[:, 4:5]
step_valid = torch.arange(longest_line, device=device).unsqueeze(0) < meta[:, 3:4]
valid = drop_valid.unsqueeze(2) & step_valid.unsqueeze(1)
- flat = valid.reshape(-1).nonzero().squeeze(1)
- batch_index = torch.div(flat, max_drops * longest_line, rounding_mode="floor")
- output[batch_index, :, drop_rows.reshape(-1)[flat], drop_cols.reshape(-1)[flat]] = 200 / 255
- return output
+ # Count the kept drop pixels per image position with a scatter and write the drop value where the count is
+ # positive: the same pixels and the same value as an indexed assignment, without the ``nonzero`` that would
+ # read the mask back on the host. Padding entries are clamped into the image and counted with weight zero;
+ # the kept ones are inside it by construction. Integer counts make the scatter order-independent.
+ position = drop_rows.clamp(0, image_height - 1) * image_width + drop_cols.clamp(0, image_width - 1)
+ hits = torch.zeros(batch_size, image_height * image_width, dtype=torch.int32, device=device)
+ hits.scatter_add_(1, position.reshape(batch_size, -1), valid.reshape(batch_size, -1).to(torch.int32))
+ drop_mask = (hits > 0).view(batch_size, 1, image_height, image_width)
+ return torch.where(drop_mask, 200 / 255, output)
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index 50c4e3472..ee1a4f587 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -23,6 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.color import hls_to_rgb, rgb_to_hls
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
class RandomSnow(IntensityAugmentationBase2D):
@@ -95,8 +96,8 @@ class RandomSnow(IntensityAugmentationBase2D):
mask = torch.zeros_like(input_HLS)
# Retrieve generated parameters
- snow_coefficient = params["snow_coefficient"].to(input)
- brightness = params["brightness"].to(input)
+ snow_coefficient = _to_device_nonblocking(params["snow_coefficient"], input.device, input.dtype)
+ brightness = _to_device_nonblocking(params["brightness"], input.device, input.dtype)
snow_coefficient = snow_coefficient[:, None, None, None]
brightness = brightness[:, None, None, None]
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index 5400f8826..5d652ea05 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation.random_generator._2d import SaltAndPepperGenerator
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
@@ -153,8 +154,12 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
noisy_image = input.clone()
- # Apply noise masks using indexing.
- noisy_image[params["mask_salt"].to(input.device)] = 1.0
- noisy_image[params["mask_pepper"].to(input.device)] = 0.0
-
- return noisy_image
+ mask_salt = _to_device_nonblocking(params["mask_salt"], input.device)
+ mask_pepper = _to_device_nonblocking(params["mask_pepper"], input.device)
+ if mask_salt.shape != noisy_image.shape or mask_pepper.shape != noisy_image.shape:
+ # Boolean indexing raises for a mask of another shape, where ``masked_fill`` would broadcast it.
+ noisy_image[mask_salt] = 1.0
+ noisy_image[mask_pepper] = 0.0
+ return noisy_image
+ # The same writes as boolean indexing, salt first, without the ``nonzero`` that reads the masks on the host.
+ return noisy_image.masked_fill(mask_salt, 1.0).masked_fill(mask_pepper, 0.0)
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 774e59af3..8ae120009 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range
from kornia.augmentation.utils import _range_bound
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import adjust_saturation
@@ -103,5 +104,5 @@ class RandomSaturation(IntensityAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
input = _clamp_unit_range(input)
- saturation_factor = params["saturation_factor"].to(input)
+ saturation_factor = _to_device_nonblocking(params["saturation_factor"], input.device, input.dtype)
return _clamp_unit_range(adjust_saturation(input, saturation_factor))
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 8c0f672d9..154702dbf 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -29,6 +29,7 @@ from kornia.augmentation.utils import (
from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
from kornia.constants import DataKey, DType
from kornia.core.check import KORNIA_UNWRAP
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.boxes import Boxes
@@ -157,7 +158,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
applied_post = self.apply_non_transform(applied, params, flags)
if applied_post.shape == non_applied.shape and applied_post.shape[0] == to_apply.shape[0]:
- to_apply_expanded = to_apply.view(-1, *([1] * (applied_post.dim() - 1))).to(applied_post.device)
+ to_apply_expanded = _to_device_nonblocking(
+ to_apply.view(-1, *([1] * (applied_post.dim() - 1))), applied_post.device
+ )
output = torch.where(to_apply_expanded, applied_post, non_applied)
else:
# Shape-changing mix augmentations (e.g. RandomMosaic when ``output_size``
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 378269d55..0d139108c 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, DType
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
@@ -143,7 +144,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
image_dtype = DType.to_torch(int(params["dtype"].item()))
calc_dtype = image_dtype if image_dtype in (torch.float32, torch.float64) else torch.float32
for pair, crop in zip(params["mix_pairs"], params["crop_src"]):
- labels_permute = input.index_select(dim=0, index=pair.to(input.device))
+ labels_permute = input.index_select(dim=0, index=_to_device_nonblocking(pair, input.device))
w, h = infer_bbox_shape(crop)
lam_val = w.to(calc_dtype) * h.to(calc_dtype) / (width * height)
@@ -154,7 +155,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
[
input.to(device=input.device, dtype=calc_dtype),
labels_permute.to(device=input.device, dtype=calc_dtype),
- lam.to(device=input.device, dtype=calc_dtype),
+ _to_device_nonblocking(lam, input.device, calc_dtype),
],
1,
)
@@ -190,7 +191,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
out_inputs = input.clone()
for pair, crop in zip(params["mix_pairs"], params["crop_src"]):
- input_permute = input.index_select(dim=0, index=pair.to(input.device))
+ input_permute = input.index_select(dim=0, index=_to_device_nonblocking(pair, input.device))
# compute mask to match input shape
mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
out_inputs[mask] = input_permute[mask]
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index 45fb2d93f..de4a18a00 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey
+from kornia.core.utils import _to_device_nonblocking
__all__ = ["RandomJigsaw"]
@@ -108,7 +109,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
.reshape(c, -1, piece_size_h, piece_size_w)
)
perm = (perm + torch.arange(0, b, device=perm.device)[:, None] * perm.shape[1]).view(-1)
- input = input[:, perm, :, :]
+ input = input[:, _to_device_nonblocking(perm, input.device), :, :]
return (
input.reshape(-1, b, self.flags["grid"][1], h, piece_size_w)
.permute(0, 1, 2, 4, 3)
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 65a253ad2..f4b253291 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -22,6 +22,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, DType
+from kornia.core.utils import _to_device_nonblocking
class RandomMixUpV2(MixAugmentationBaseV2):
@@ -122,9 +123,12 @@ class RandomMixUpV2(MixAugmentationBaseV2):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
- input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
+ input_permute = input.index_select(dim=0, index=_to_device_nonblocking(params["mixup_pairs"], input.device))
- lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(input.device, dtype=input.dtype)
+ # Moved before it is expanded: the copy is B values instead of a full-size buffer, and every element of the
+ # broadcast holds the same value either way.
+ lam = _to_device_nonblocking(params["mixup_lambdas"].view(-1, 1, 1, 1), input.device, input.dtype)
+ lam = lam.expand_as(input)
return input * (1 - lam) + input_permute * lam
def apply_non_transform_class(
@@ -144,7 +148,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
def apply_transform_class(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], maybe_flags: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
- labels_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
+ labels_permute = input.index_select(dim=0, index=_to_device_nonblocking(params["mixup_pairs"], input.device))
image_dtype = DType.to_torch(int(params["dtype"].item()))
calc_dtype = image_dtype if image_dtype in (torch.float32, torch.float64) else torch.float32
@@ -152,7 +156,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
[
input.to(device=input.device, dtype=calc_dtype),
labels_permute.to(device=input.device, dtype=calc_dtype),
- params["mixup_lambdas"].to(device=input.device, dtype=calc_dtype),
+ _to_device_nonblocking(params["mixup_lambdas"], input.device, calc_dtype),
],
-1,
)
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 84b74a9ca..e25dca9f7 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -25,7 +25,7 @@ from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, Resample
from kornia.core.check import KORNIA_UNWRAP
from kornia.core.ops import eye_like
-from kornia.core.utils import is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
@@ -218,7 +218,7 @@ class RandomMosaic(MixAugmentationBaseV2):
out_row = []
for j in range(flags["mosaic_grid"][1]):
img_idx = flags["mosaic_grid"][1] * i + j
- image = input[params["permutation"][:, img_idx]]
+ image = input[_to_device_nonblocking(params["permutation"][:, img_idx], input.device)]
out_row.append(image)
out.append(torch.cat(out_row, -2))
return torch.cat(out, -1)
@@ -227,7 +227,9 @@ class RandomMosaic(MixAugmentationBaseV2):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
if flags["cropping_mode"] == "resample":
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ transform: torch.Tensor = get_perspective_transform(src, dst)
return transform
if flags["cropping_mode"] == "slice": # Skip the computation for slicing.
return eye_like(3, input)
diff --git a/kornia/augmentation/_2d/mix/patchmix.py b/kornia/augmentation/_2d/mix/patchmix.py
index 9b9bbb775..ed9cff2bd 100644
--- a/kornia/augmentation/_2d/mix/patchmix.py
+++ b/kornia/augmentation/_2d/mix/patchmix.py
@@ -85,13 +85,14 @@ class PatchMix(MixAugmentationBaseV2):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], extra_args: Dict[str, Any]
) -> torch.Tensor:
B, _, _, _ = input.shape
- idx = params["mix_pairs"].to(input.device)
- patch_coords = params["patch_coords"].to(input.device)
+ # The pairs and corners index Python slices, so read them where they were drawn: on the CPU that costs no
+ # device synchronization, while reading them from the GPU would cost one per sample.
+ idx = params["mix_pairs"].tolist()
+ patch_coords = params["patch_coords"].tolist()
out = input.clone()
for i in range(B):
- x, y = patch_coords[i]
- x, y = int(x.item()), int(y.item())
+ x, y = int(patch_coords[i][0]), int(patch_coords[i][1])
out[i, :, y : y + self.patch_size, x : x + self.patch_size] = input[
idx[i], :, y : y + self.patch_size, x : x + self.patch_size
]
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 63131419f..f6d7e5b35 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -25,6 +25,7 @@ from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.augmentation.utils import _validate_input_dtype
from kornia.constants import DataKey
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _to_device_nonblocking
__all__ = ["RandomTransplantation"]
@@ -234,16 +235,17 @@ class RandomTransplantation(MixAugmentationBaseV2):
def transform_input(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor:
# Expand selection to the channel dimension
- selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)
- acceptor[selection] = donor[selection]
- return acceptor
+ selection = _to_device_nonblocking(selection, acceptor.device).unsqueeze(dim=self._channel_dim).expand_as(donor)
+ # The same values as ``acceptor[selection] = donor[selection]``, without the ``nonzero`` that boolean indexing
+ # runs, which reads the selection back on the host.
+ return torch.where(selection, donor, acceptor)
def transform_mask(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor:
if acceptor.ndim == selection.ndim + 1:
# A mask with a singleton channel axis, ``(B, 1, *spatial)``, as a container hands it on (#4707).
selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)
- acceptor[selection] = donor[selection]
- return acceptor
+ # As in ``transform_input``: a ``where`` instead of boolean indexing, which reads the selection on the host.
+ return torch.where(_to_device_nonblocking(selection, acceptor.device), donor, acceptor)
def _check_mask_given(self, input: Sequence[torch.Tensor], data_keys: list[DataKey]) -> None:
# The parameters are drawn from the mask, so name it before any lookup fails on its absence.
@@ -407,8 +409,10 @@ class RandomTransplantation(MixAugmentationBaseV2):
outputs: list[torch.Tensor] = []
for dcate, _input in zip(keys, input):
- acceptor = _input[self._params["acceptor_indices"]].clone()
- donor = _input[self._params["donor_indices"]]
+ # The indices are drawn on the CPU; indexing device data with them would copy them with a blocking transfer.
+ acceptor_indices = _to_device_nonblocking(self._params["acceptor_indices"], _input.device)
+ acceptor = _input[acceptor_indices].clone()
+ donor = _input[_to_device_nonblocking(self._params["donor_indices"], _input.device)]
output: torch.Tensor
if dcate == DataKey.INPUT:
@@ -419,14 +423,14 @@ class RandomTransplantation(MixAugmentationBaseV2):
applied = self.transform_input(acceptor, donor, self._params["selection"])
output = self.apply_non_transform(_input, self._params, self.flags)
output = output.index_put(
- (self._params["acceptor_indices"],),
+ (acceptor_indices,),
self.apply_non_transform_mask(applied, self._params, self.flags),
)
elif dcate == DataKey.MASK:
applied = self.transform_mask(acceptor, donor, self._params["selection"])
output = self.apply_non_transform_mask(_input, self._params, self.flags)
output = output.index_put(
- (self._params["acceptor_indices"],),
+ (acceptor_indices,),
self.apply_non_transform_mask(applied, self._params, self.flags),
)
else:
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 67717e557..037030bfd 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -23,6 +23,7 @@ from torch import float16, float32, float64
import kornia
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.boxes import Boxes3D
from kornia.geometry.keypoints import Keypoints3D
@@ -123,8 +124,8 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
trans_matrix_identity = self.identity_matrix(in_tensor)
if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:
- to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))).to(
- trans_matrix_applied.device
+ to_apply_expanded = _to_device_nonblocking(
+ to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))), trans_matrix_applied.device
)
trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)
else:
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index a7e0fc17b..5bfcfea18 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -23,6 +23,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform.imgwarp import get_affine_matrix3d, warp_affine3d
@@ -177,8 +178,9 @@ class RandomAffine3D(GeometricAugmentationBase3D):
params["syz"] * deg2rad_factor,
params["szx"] * deg2rad_factor,
params["szy"] * deg2rad_factor,
- ).to(input)
- return transform
+ )
+ # Built from the CPU parameters, then moved once without waiting for the queued kernels.
+ return _to_device_nonblocking(transform, input.device, input.dtype)
def apply_transform(
self,
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 94ab4bf2a..966d2bdbe 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -23,6 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.augmentation._3d.geometric.crop import _crop_translation3d
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry import crop_by_transform_mat3d
@@ -120,7 +121,9 @@ class CenterCrop3D(GeometricAugmentationBase3D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- transform = _crop_translation3d(params["src"].to(input), params["dst"].to(input))
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ transform = _crop_translation3d(src, dst)
return transform.expand(input.shape[0], -1, -1)
def apply_transform(
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 6b52109fa..232fe065d 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -25,6 +25,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.augmentation.utils.helpers import _pad_with_fill
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry import crop_by_transform_mat3d
@@ -188,7 +189,9 @@ class RandomCrop3D(GeometricAugmentationBase3D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- transform = _crop_translation3d(params["src"].to(input), params["dst"].to(input))
+ src = _to_device_nonblocking(params["src"], input.device, input.dtype)
+ dst = _to_device_nonblocking(params["dst"], input.device, input.dtype)
+ transform = _crop_translation3d(src, dst)
for padding in self._compute_padding(tuple(input.shape), flags):
transform[:, 0, 3] += padding[0]
transform[:, 1, 3] += padding[2]
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 2e894690a..4efb7acb8 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -21,6 +21,7 @@ import torch
from torch import Tensor
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
+from kornia.core.ops import _device_literal
class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
@@ -81,8 +82,16 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
d: int = input.shape[-3]
- flip_mat: Tensor = torch.tensor(
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ # Filled on the device in eager mode: a ``torch.tensor`` literal copies from the host and waits for queued
+ # kernels. ``torch.jit.trace`` can pass the size as a 0-d tensor, which keeps the literal.
+ flip_mat: Tensor = (
+ _device_literal(
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ if isinstance(d, int)
+ else torch.tensor(
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
)
return flip_mat.expand(input.shape[0], 4, 4)
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index 37cc4d8af..84a8c5079 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -21,6 +21,7 @@ import torch
from torch import Tensor
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
+from kornia.core.ops import _device_literal
class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
@@ -79,8 +80,16 @@ class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
w: int = input.shape[-1]
- flip_mat: Tensor = torch.tensor(
- [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ # Filled on the device in eager mode: a ``torch.tensor`` literal copies from the host and waits for queued
+ # kernels. ``torch.jit.trace`` can pass the size as a 0-d tensor, which keeps the literal.
+ flip_mat: Tensor = (
+ _device_literal(
+ [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ if isinstance(w, int)
+ else torch.tensor(
+ [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
)
return flip_mat.expand(input.shape[0], 4, 4)
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 15c7f46aa..740647a4f 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -23,6 +23,7 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry import get_perspective_transform3d, warp_perspective3d
@@ -127,7 +128,7 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
elif isinstance(width, int) and width == 1:
order = [0, 4, 7, 3, 1, 5, 6, 2] if depth > 1 else [0, 3, 2, 1, 4, 7, 6, 5]
start_points, end_points = start_points[:, order], end_points[:, order]
- return get_perspective_transform3d(start_points, end_points).to(input)
+ return _to_device_nonblocking(get_perspective_transform3d(start_points, end_points), input.device, input.dtype)
def apply_transform(
self,
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 898c21225..f7d3617df 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -23,6 +23,7 @@ import kornia
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
+from kornia.core.utils import _to_device_nonblocking
from kornia.geometry import affine3d
from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
@@ -124,9 +125,9 @@ class RandomRotation3D(GeometricAugmentationBase3D):
def compute_transformation(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- yaw: torch.Tensor = params["yaw"].to(input)
- pitch: torch.Tensor = params["pitch"].to(input)
- roll: torch.Tensor = params["roll"].to(input)
+ yaw: torch.Tensor = _to_device_nonblocking(params["yaw"], input.device, input.dtype)
+ pitch: torch.Tensor = _to_device_nonblocking(params["pitch"], input.device, input.dtype)
+ roll: torch.Tensor = _to_device_nonblocking(params["roll"], input.device, input.dtype)
center: torch.Tensor = _compute_tensor_center3d(input)
rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index a379286cf..26f8225f0 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -21,6 +21,7 @@ import torch
from torch import Tensor
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
+from kornia.core.ops import _device_literal
class RandomVerticalFlip3D(GeometricAugmentationBase3D):
@@ -81,8 +82,16 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
h: int = input.shape[-2]
- flip_mat: Tensor = torch.tensor(
- [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ # Filled on the device in eager mode: a ``torch.tensor`` literal copies from the host and waits for queued
+ # kernels. ``torch.jit.trace`` can pass the size as a 0-d tensor, which keeps the literal.
+ flip_mat: Tensor = (
+ _device_literal(
+ [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ if isinstance(h, int)
+ else torch.tensor(
+ [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
)
return flip_mat.expand(input.shape[0], 4, 4)
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 4b3c0d77c..7463b3d4d 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -21,6 +21,7 @@ import torch
from torch import nn
from kornia.augmentation.base import _AugmentationBase
+from kornia.core.utils import _to_device_nonblocking
T = TypeVar("T", bound="OperationBase")
@@ -182,8 +183,8 @@ class OperationBase(nn.Module):
if params is None:
params = self.forward_parameters(input.shape)
- batch_prob = params["batch_prob"][(...,) + ((None,) * (len(input.shape) - 1))].to(
- device=input.device, dtype=input.dtype
+ batch_prob = _to_device_nonblocking(
+ params["batch_prob"][(...,) + ((None,) * (len(input.shape) - 1))], input.device, input.dtype
)
# The wrapped augmentation transforms every row the blend gives a weight, so a fractional gate is not
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 16a40ac9e..29c88447f 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -30,7 +30,7 @@ from kornia.augmentation.utils import (
override_parameters,
)
from kornia.augmentation.utils.helpers import _constant_tensor
-from kornia.core.utils import is_autocast_enabled, is_exporting
+from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -405,7 +405,9 @@ class _AugmentationBase(_BasicAugmentationBase):
rows raises ``ValueError`` instead of transforming the skipped rows too.
"""
if transformed.shape == not_transformed.shape and transformed.shape[0] == to_apply.shape[0]:
- to_apply_expanded = to_apply.view(-1, *([1] * (len(transformed.shape) - 1))).to(transformed.device)
+ to_apply_expanded = _to_device_nonblocking(
+ to_apply.view(-1, *([1] * (len(transformed.shape) - 1))), transformed.device
+ )
return torch.where(to_apply_expanded, transformed, not_transformed)
apply_any = bool(to_apply.any())
if apply_any and not bool(to_apply.all()) and transformed.shape[1:] != not_transformed.shape[1:]:
@@ -453,7 +455,7 @@ class _AugmentationBase(_BasicAugmentationBase):
to_apply = torch.atleast_1d(params["batch_prob"] > 0.5)
transform_input = in_tensor
if self.SUBSTITUTE_SKIPPED_SAMPLES:
- gate = to_apply.view(-1, *([1] * (in_tensor.ndim - 1))).to(in_tensor.device)
+ gate = _to_device_nonblocking(to_apply.view(-1, *([1] * (in_tensor.ndim - 1))), in_tensor.device)
transform_input = torch.where(gate, in_tensor, 0.5)
output_transformed = self.apply_transform(transform_input, params, flags, transform=transform)
output_not_transformed = self.apply_non_transform(in_tensor, params, flags, transform=transform)
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index c5fe14f89..bf7f06c1f 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -27,6 +27,8 @@ import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
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
@@ -38,6 +40,23 @@ 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"""Container for performing patch-level image data augmentation.
@@ -434,10 +453,11 @@ class PatchSequential(ImageSequential):
for patch_param in params:
# input, out_param = self.apply_by_param(input, params=patch_param)
module = self.get_submodule(patch_param.param.name)
- _input = input[patch_param.indices]
+ 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[patch_param.indices] = output.to(input)
+ input[indices] = output.to(input)
return input.reshape(in_shape)
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 7625481f0..d89434cbf 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -15,7 +15,6 @@
# limitations under the License.
#
-import math
from functools import wraps
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
@@ -23,6 +22,8 @@ import torch
import torch.nn.functional as F
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.ops import _constant_tensor, _flatten_constant # noqa: F401
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -58,16 +59,6 @@ def _pad_with_fill(
return torch.where(inside.bool(), padded, values.view(1, channels, *([1] * (padded.ndim - 2))))
-def _flatten_constant(data: Any, shape: List[int], leaves: List[Any], depth: int = 0) -> None:
- if isinstance(data, (list, tuple)):
- if depth == len(shape):
- shape.append(len(data))
- for value in data:
- _flatten_constant(value, shape, leaves, depth + 1)
- else:
- leaves.append(data)
-
-
def _boxes_to_padded_tensor(boxes: Boxes, mode: str) -> torch.Tensor:
"""Export ``boxes`` as one dense tensor whose trailing padding rows are exactly zero.
@@ -88,52 +79,6 @@ def _boxes_to_padded_tensor(boxes: Boxes, mode: str) -> torch.Tensor:
return torch.where(valid, out, torch.zeros((), device=out.device, dtype=out.dtype))
-def _constant_tensor(
- data: Union[float, List[Any], Tuple[Any, ...]],
- *,
- device: Union[str, torch.device, None] = None,
- dtype: torch.dtype,
-) -> torch.Tensor:
- """Construct small numeric constants inside the graph, without lifting tensor storage.
-
- Inductor can reuse a lifted CPU tensor in a CUDA kernel without transferring it
- (https://github.com/pytorch/pytorch/issues/196969). Scalar factories and stacks
- avoid that path, including for constants returned alongside CUDA tensors. Indexed
- scalar writes are unsafe too: tracing lifts their right-hand sides.
-
- Eager execution, Dynamo and ``make_fx`` all run this same construction, which issues
- no host-device copy. Each distinct Python scalar is filled once and a single stack
- reuses it, so repeated coordinates such as box corners cost one kernel per value.
-
- ``data`` contains Python scalars or rectangular nested lists/tuples, never tensors.
- Other array-likes, such as NumPy arrays, keep ``torch.as_tensor`` semantics. Callers
- choose dtype explicitly and perform coordinate arithmetic before calling this helper
- when rounding before versus after casting matters.
- """
- if not isinstance(data, (list, tuple)):
- if isinstance(data, (int, float, torch.SymInt, torch.SymFloat)):
- return torch.full((), data, device=device, dtype=dtype)
- return torch.as_tensor(data, device=device, dtype=dtype)
- shape: List[int] = []
- leaves: List[Any] = []
- _flatten_constant(data, shape, leaves)
- if not leaves:
- return torch.empty(shape, device=device, dtype=dtype)
- filled: Dict[Tuple[type, Any], torch.Tensor] = {}
- values: List[torch.Tensor] = []
- for leaf in leaves:
- # Symbolic sizes stay unmerged because comparing them adds guards. The float key carries
- # the sign because -0.0 == 0.0; NaN is filled per leaf because NaN != NaN.
- if type(leaf) in (int, bool) or (type(leaf) is float and not math.isnan(leaf)):
- key = (type(leaf), leaf, math.copysign(1.0, leaf))
- if key not in filled:
- filled[key] = torch.full((), leaf, device=device, dtype=dtype)
- values.append(filled[key])
- else:
- values.append(torch.full((), leaf, device=device, dtype=dtype))
- return torch.stack(values).view(shape)
-
-
def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 2D input of the wrapped function.
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index a5afb64df..503a271d7 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -24,6 +24,8 @@ from torch import nn
from kornia.color.rgb import bgr_to_rgb
from kornia.core.check import KORNIA_CHECK_IS_TENSOR
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking
def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:
@@ -104,12 +106,18 @@ def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] =
return ((acc + 16384) // 32768).to(dtype=torch.uint8).unsqueeze(-3)
# floating point images
if image.dtype in (torch.bfloat16, torch.float16, torch.float32, torch.float64):
- rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)
+ # Filled on the device in eager mode: ``torch.tensor(..., device=cuda)`` copies from the host and waits
+ # for every queued kernel. The weights round from the same doubles either way. TorchScript, which cannot
+ # compile ``_constant_tensor``, keeps the host literal.
+ if torch.jit.is_scripting():
+ rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)
+ else:
+ rgb_weights = _device_literal([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)
else:
raise TypeError(f"Unknown data type: {image.dtype}")
else:
# is torch.Tensor that we make sure is in the same device/dtype
- rgb_weights = rgb_weights.to(image)
+ rgb_weights = _to_device_nonblocking(rgb_weights, image.device, image.dtype)
# Unpack channels (View, don't copy)
r, g, b = image.unbind(dim=-3)
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index a79d37224..5909c9bc8 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -23,6 +23,8 @@ from typing import ClassVar
import torch
from torch import nn
+from kornia.core.ops import _device_literal
+
def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Convert an RGB image to HLS.
@@ -57,7 +59,12 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- _RGB2HSL_IDX = torch.tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+ # 3x1x1. Filled on the device in eager mode: ``torch.tensor(..., device=cuda)`` copies from the host and waits
+ # for every queued kernel. TorchScript, which cannot compile ``_constant_tensor``, keeps the host literal.
+ if torch.jit.is_scripting():
+ _RGB2HSL_IDX = torch.tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype)
+ else:
+ _RGB2HSL_IDX = _device_literal([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype)
_img_max: tuple[torch.Tensor, torch.Tensor] = image.max(-3)
maxc = _img_max[0]
@@ -123,7 +130,11 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- _HLS2RGB = torch.tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1
+ # 3x1x1, filled on the device in eager mode as in ``rgb_to_hls``.
+ if torch.jit.is_scripting():
+ _HLS2RGB = torch.tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype)
+ else:
+ _HLS2RGB = _device_literal([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype)
im: torch.Tensor = image.unsqueeze(-4)
h_ch: torch.Tensor = im[..., 0, :, :]
diff --git a/kornia/core/ops.py b/kornia/core/ops.py
index 1ee743cf4..083026be7 100644
--- a/kornia/core/ops.py
+++ b/kornia/core/ops.py
@@ -15,13 +15,15 @@
# limitations under the License.
#
+import math
import operator
-from typing import Any
+from typing import Any, Dict, List, Tuple, Union
import torch
from kornia.core.check import KORNIA_CHECK, are_checks_enabled
from kornia.core.exceptions import TypeCheckError
+from kornia.core.utils import is_compiling
def _is_numpy_bool(n: Any) -> bool:
@@ -133,3 +135,104 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)
+
+
+def _flatten_constant(data: Any, shape: List[int], leaves: List[Any], depth: int = 0) -> None:
+ if isinstance(data, (list, tuple)):
+ if depth == len(shape):
+ shape.append(len(data))
+ for value in data:
+ _flatten_constant(value, shape, leaves, depth + 1)
+ else:
+ leaves.append(data)
+
+
+def _constant_tensor(
+ data: Union[float, List[Any], Tuple[Any, ...]],
+ *,
+ device: Union[str, torch.device, None] = None,
+ dtype: torch.dtype,
+) -> torch.Tensor:
+ """Construct small numeric constants inside the graph, without lifting tensor storage.
+
+ Inductor can reuse a lifted CPU tensor in a CUDA kernel without transferring it
+ (https://github.com/pytorch/pytorch/issues/196969). Scalar factories and stacks
+ avoid that path, including for constants returned alongside CUDA tensors. Indexed
+ scalar writes are unsafe too: tracing lifts their right-hand sides.
+
+ Eager execution, Dynamo and ``make_fx`` all run this same construction, which issues
+ no host-device copy. Each distinct Python scalar is filled once and a single stack
+ reuses it, so repeated coordinates such as box corners cost one kernel per value.
+
+ ``data`` contains Python scalars or rectangular nested lists/tuples, never tensors.
+ Other array-likes, such as NumPy arrays, keep ``torch.as_tensor`` semantics. Callers
+ choose dtype explicitly and perform coordinate arithmetic before calling this helper
+ when rounding before versus after casting matters.
+ """
+ if not isinstance(data, (list, tuple)):
+ if isinstance(data, (int, float, torch.SymInt, torch.SymFloat)):
+ return torch.full((), data, device=device, dtype=dtype)
+ return torch.as_tensor(data, device=device, dtype=dtype)
+ shape: List[int] = []
+ leaves: List[Any] = []
+ _flatten_constant(data, shape, leaves)
+ if not leaves:
+ return torch.empty(shape, device=device, dtype=dtype)
+ filled: Dict[Tuple[type, Any], torch.Tensor] = {}
+ values: List[torch.Tensor] = []
+ for leaf in leaves:
+ # Symbolic sizes stay unmerged because comparing them adds guards. The float key carries
+ # the sign because -0.0 == 0.0; NaN is filled per leaf because NaN != NaN.
+ if type(leaf) in (int, bool) or (type(leaf) is float and not math.isnan(leaf)):
+ key = (type(leaf), leaf, math.copysign(1.0, leaf))
+ if key not in filled:
+ filled[key] = torch.full((), leaf, device=device, dtype=dtype)
+ values.append(filled[key])
+ else:
+ values.append(torch.full((), leaf, device=device, dtype=dtype))
+ return _stack_without_autocast(values).view(shape)
+
+
+# The device types whose autocast state torch can report; ``torch.is_autocast_enabled("meta")`` raises.
+_AUTOCAST_DEVICE_TYPES = ("cpu", "cuda", "mps", "xpu", "xla", "hpu")
+
+
+def _stack_without_autocast(values: List[torch.Tensor]) -> torch.Tensor:
+ """Stack ``values`` in their own dtype, also inside an autocast region.
+
+ ``torch.stack`` is on autocast's promote list, which rejects a half dtype other than the region's own (a
+ ``float16`` stack inside CPU autocast, whose lower precision is ``bfloat16``). A literal keeps the dtype it was
+ asked for, as ``torch.tensor`` does, so autocast is switched off for the stack.
+ """
+ device_type = values[0].device.type
+ if device_type in _AUTOCAST_DEVICE_TYPES and torch.is_autocast_enabled(device_type):
+ with torch.autocast(device_type, enabled=False):
+ return torch.stack(values)
+ return torch.stack(values)
+
+
+def _device_literal(
+ data: Union[float, List[Any], Tuple[Any, ...]], *, device: Union[str, torch.device, None], dtype: torch.dtype
+) -> torch.Tensor:
+ """Return ``torch.tensor(data, device=device, dtype=dtype)`` for a literal of Python numbers, without a host sync.
+
+ An eager call fills the literal on the device with :func:`_constant_tensor`: ``torch.tensor(..., device=cuda)``
+ copies it from the host and waits for every queued kernel. Under ``torch.compile`` and ``torch.export`` the literal
+ stays ``torch.tensor(..., device=device)``, as before: capture makes it a constant of the graph on ``device``, which
+ costs no copy at run time and which Inductor folds into its consumer, where filled values would add kernels. Both
+ round the same Python numbers to ``dtype``, so the values are the same.
+ """
+ if is_compiling() or (dtype == torch.float16 and not _fits_float16(data)):
+ return torch.tensor(data, device=device, dtype=dtype)
+ return _constant_tensor(data, device=device, dtype=dtype)
+
+
+def _fits_float16(data: Union[float, List[Any], Tuple[Any, ...]]) -> bool:
+ """Whether every finite number in ``data`` is within the float16 range.
+
+ ``torch.full`` raises for a finite value beyond it on CUDA (and on the CPU in torch 2.5.1), where ``torch.tensor``
+ rounds it to 65504 or to infinity, so such a literal keeps ``torch.tensor``.
+ """
+ leaves: List[Any] = []
+ _flatten_constant(data, [], leaves)
+ return all(not isinstance(v, (int, float)) or not math.isfinite(v) or abs(v) <= 65504.0 for v in leaves)
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 1cba4fbb0..9927c6761 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -62,6 +62,60 @@ def _torch_grid_sample(
return F.grid_sample(input, grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+def _to_device_nonblocking(
+ tensor: torch.Tensor, device: torch.device, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
+ """Move ``tensor`` to ``device`` (and ``dtype``), without waiting for queued work on a CUDA target.
+
+ A blocking host-to-device copy from pageable memory ends in ``cudaStreamSynchronize``, so the host waits
+ until the GPU has finished everything queued before it. With ``non_blocking=True`` CUDA stages a pageable
+ source before the call returns, so the source may be changed or freed straight away. A dtype change is made
+ on the host before the copy, as the blocking copy makes it, so the copied bits are the same, NaN payloads
+ included.
+
+ Only an eager copy from pageable CPU memory to CUDA is non-blocking:
+
+ - A pinned source is copied asynchronously by a non-blocking copy and could be changed by its owner before the
+ copy lands, so it keeps the blocking copy.
+ - Under ``torch.compile`` and ``torch.export`` the copy stays blocking, as it was: Inductor (torch 2.14)
+ miscompiles a non-blocking copy of a CPU tensor computed inside the graph, such as parameters sampled in a
+ compiled ``forward``, and returns wrong values.
+ - A copy to the CPU stays blocking, because the host could otherwise read it before it arrives, and MPS and
+ other targets keep the blocking copy, since they may read the source after the call returns.
+
+ Args:
+ tensor: The tensor to move.
+ device: The target device.
+ dtype: The target dtype, or ``None`` to keep the dtype of ``tensor``.
+
+ Returns:
+ ``tensor`` itself when it already has the target device and dtype, a copy otherwise.
+ """
+ if torch.jit.is_scripting():
+ non_blocking = tensor.device.type == "cpu" and device.type == "cuda" and not tensor.is_pinned()
+ else:
+ non_blocking = (
+ tensor.device.type == "cpu" and device.type == "cuda" and not is_compiling() and not tensor.is_pinned()
+ )
+ if non_blocking:
+ if dtype is not None and dtype != tensor.dtype:
+ tensor = tensor.to(dtype=dtype)
+ return tensor.to(device=device, non_blocking=True)
+ return tensor.to(device=device, dtype=dtype)
+
+
+def _as_tensor_nonblocking(data: Any, device: torch.device, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
+ """Return ``torch.as_tensor(data, device=device, dtype=dtype)``, moving a tensor without waiting for the GPU.
+
+ ``torch.as_tensor`` of a tensor is ``tensor.to(device, dtype)``, a blocking copy for a CPU tensor and a CUDA
+ ``device``. A tensor is moved without waiting for queued work instead, with the same values; any other ``data``
+ goes through ``torch.as_tensor`` unchanged.
+ """
+ if isinstance(data, torch.Tensor):
+ return _to_device_nonblocking(data, device, dtype)
+ return torch.as_tensor(data, device=device, dtype=dtype)
+
+
def xla_is_available() -> bool:
"""Return whether `torch_xla` is available in the system."""
return importlib.util.find_spec("torch_xla") is not None
@@ -339,7 +393,7 @@ def _times_power_of_two(x: torch.Tensor, exponent: torch.Tensor) -> torch.Tensor
return x * scale * scale * powers[(exponent - 2 * step + largest).to(torch.int64)]
-def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
+def _torch_inverse_cast(input: torch.Tensor, check_errors: bool = True) -> torch.Tensor:
"""Make torch.inverse work with other than fp32/64.
The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
@@ -357,11 +411,18 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
non-finite or large values. Which near-singular matrices raise, and which return large values, depends
on the torch version, the device and the capture mode. Callers that need a verdict use
:func:`safe_inverse_with_mask`, whose mask follows one rule everywhere.
+
+ ``torch.linalg.inv`` reads its factorization status back on the host to raise for a singular matrix, which on
+ CUDA waits for every queued kernel. ``check_errors=False`` uses ``torch.linalg.inv_ex`` instead: the same
+ factorization and the same bits, without the read. Pass it only for a matrix that cannot be singular, such as a
+ pixel normalization kornia builds itself; a singular matrix then returns non-finite values instead of raising.
"""
KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
dtype = _normalize_to_float32_or_float64(input.dtype)
if _is_tracing_or_exporting() and _has_closed_form_inverse(input):
return _closed_form_inverse(input.to(dtype)).to(input.dtype)
+ if not check_errors:
+ return inv_ex(input.to(dtype)).inverse.to(input.dtype)
return torch.linalg.inv(input.to(dtype)).to(input.dtype)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index ef77aa501..fee9eadad 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -34,7 +34,8 @@ from kornia.core.check import (
are_checks_enabled,
)
from kornia.core.exceptions import TypeCheckError
-from kornia.core.utils import _normalize_to_float32_or_float64, is_compiling
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonblocking, is_compiling
from kornia.image.utils import _to_bcdhw, _to_bchw
@@ -139,7 +140,7 @@ def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -200,7 +201,7 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[f
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -264,7 +265,7 @@ def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -
if isinstance(factor, float):
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
else:
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
if factor.shape[-3] != 1:
@@ -305,7 +306,7 @@ def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> t
if isinstance(factor, float):
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -535,7 +536,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -593,7 +594,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -665,7 +666,7 @@ def adjust_brightness(
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -723,7 +724,7 @@ def adjust_brightness_accumulative(
# TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
- factor = factor.to(image.device, image.dtype)
+ factor = _to_device_nonblocking(factor, image.device, image.dtype)
factor = _make_factor_broadcastable(factor, image)
@@ -837,7 +838,7 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
raise AssertionError(f"thresholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}")
# Reshape the per-sample threshold to broadcast over (C, H, W) rather than iterating the
# tensor (`for x in thresholds` breaks torch.compile); the `where` below broadcasts identically.
- thresholds = thresholds.to(input.device).to(input.dtype)
+ thresholds = _to_device_nonblocking(thresholds, input.device).to(input.dtype)
thresholds = thresholds.view([-1] + [1] * (input.ndim - 1))
return torch.where(input < thresholds, input, 1.0 - input)
@@ -926,7 +927,7 @@ def solarize(
raise AssertionError(f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}")
# Broadcast the per-sample scalar over (C, H, W) by reshaping instead of iterating the
# tensor (`for x in additions` breaks the graph); numerically identical.
- additions = additions.to(input.device).to(input.dtype)
+ additions = _to_device_nonblocking(additions, input.device).to(input.dtype)
additions = additions.view([-1] + [1] * (input.ndim - 1))
input = input + additions
input = input.clamp(0.0, 1.0)
@@ -1085,12 +1086,16 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
input_shape = input.shape
input = batched_input
- if not isinstance(factor, torch.Tensor):
+ if isinstance(factor, (int, float)):
+ # Filled on the device: ``torch.as_tensor(..., device=cuda)`` copies from the host and waits for every
+ # queued kernel.
+ factor = _device_literal(factor, device=input.device, dtype=input.dtype)
+ elif not isinstance(factor, torch.Tensor):
factor = torch.as_tensor(factor, device=input.device, dtype=input.dtype)
else:
# Match the input's device/dtype (as adjust_brightness/contrast do). Augmentation
# generators may sample the factor on a different device (e.g. CPU) than the image.
- factor = factor.to(device=input.device, dtype=input.dtype)
+ factor = _to_device_nonblocking(factor, input.device, input.dtype)
if len(factor.size()) != 0 and factor.shape != torch.Size([input.size(0)]):
raise AssertionError(
@@ -1099,7 +1104,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
)
kernel = (
- torch.as_tensor([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=input.dtype, device=input.device)
+ _device_literal([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=input.dtype, device=input.device)
.view(1, 1, 3, 3)
.repeat(input.size(1), 1, 1, 1)
/ 13
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 7dee647d0..590b7945e 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -23,7 +23,7 @@ from typing import Tuple, Union
import torch
import torch.nn.functional as F
-from kornia.core.utils import _normalize_to_float32_or_float64
+from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonblocking
from kornia.image.utils import perform_keep_shape_image
from .adjust import _check_floating_image, _lookup_value_check
@@ -248,13 +248,18 @@ def _compute_luts(
# then cast: a single clip.to("cpu", torch.float64) from MPS raises on torch 2.5.1 and returns zeros on 2.14.
limits = clip.cpu().double() if clip.device.type == "mps" else clip.double()
max_vals = (limits * pixels).div(num_bins, rounding_mode="floor").clamp(min=1)
- max_vals = max_vals.to(histos).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)
+ max_vals = (
+ _to_device_nonblocking(max_vals, histos.device, histos.dtype)
+ .view(b, 1)
+ .expand(b, gh * gw * c)
+ .reshape(-1, 1)
+ )
limited = histos.clamp(max=max_vals)
clipped_tensor = torch.relu(histos - max_vals).sum(1) if diff else pixels - limited.sum(1)
residual_tensor = torch.remainder(clipped_tensor, num_bins)
limited = limited + ((clipped_tensor - residual_tensor) / num_bins).unsqueeze(1)
limited = limited + _spread_residual(residual_tensor, num_bins)
- enabled = (clip > 0).to(device=histos.device).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)
+ enabled = _to_device_nonblocking(clip > 0, histos.device).view(b, 1).expand(b, gh * gw * c).reshape(-1, 1)
histos = torch.where(enabled, limited, histos)
elif clip > 0.0:
max_val: float = max(clip * pixels // num_bins, 1)
@@ -311,6 +316,10 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
i_idxs = torch.tensor([[0, 1, 0, 1], [-1, 0, -1, 0]] * ((gw - 2) // 2)) # reminder + i_idxs[:, [0, 2]] -= 1
i_idxs += i_floor
+ # The index tensors are built on the CPU; indexing CUDA LUTs with them would copy them with a blocking transfer.
+ j_idxs = _to_device_nonblocking(j_idxs, luts.device)
+ i_idxs = _to_device_nonblocking(i_idxs, luts.device)
+
# selection of luts to interpolate each patch
# create a tensor with dims: interp_patches height and width x 4 x num channels x bins in the histograms
# the tensor is init to -1 to denote non init hists
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index f990dd6fb..f8fb99235 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -26,7 +26,8 @@ from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
-from kornia.core.utils import is_compiling, is_exporting
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking, is_compiling, is_exporting
from kornia.enhance.adjust import _check_floating_image
from kornia.geometry.transform.affwarp import rescale
from kornia.image.utils import perform_keep_shape_image
@@ -35,6 +36,12 @@ _DCT8_CACHE: dict[
tuple[Union[torch.dtype, None], Union[str, torch.device, None]], tuple[torch.Tensor, torch.Tensor]
] = {}
+# The default quantization tables of eager calls, per (dtype, device): built once, as a filled literal of 64 values
+# costs a kernel per distinct value. They are only read.
+_DEFAULT_QT_CACHE: dict[
+ tuple[Union[torch.dtype, None], Union[str, torch.device, None]], tuple[torch.Tensor, torch.Tensor]
+] = {}
+
__all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"]
@@ -98,7 +105,8 @@ def _differentiable_clipping(
def _get_default_qt_y(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:
"""Generate default Quantization table of Y channel."""
- return torch.tensor(
+ # Filled on the device: ``torch.tensor(..., device=cuda)`` copies from the host and waits for queued kernels.
+ return _device_literal(
[
[16, 11, 10, 16, 24, 40, 51, 61],
[12, 12, 14, 19, 26, 58, 60, 55],
@@ -116,7 +124,8 @@ def _get_default_qt_y(device: Union[str, torch.device, None], dtype: Union[torch
def _get_default_qt_c(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:
"""Generate default Quantization table of C channels."""
- return torch.tensor(
+ # Filled on the device: ``torch.tensor(..., device=cuda)`` copies from the host and waits for queued kernels.
+ return _device_literal(
[
[17, 18, 24, 47, 99, 99, 99, 99],
[18, 21, 26, 66, 99, 99, 99, 99],
@@ -132,6 +141,28 @@ def _get_default_qt_c(device: Union[str, torch.device, None], dtype: Union[torch
)
+def _default_quantization_tables(
+ device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Return the default Y and C quantization tables, cached per (dtype, device) in eager mode.
+
+ As in :func:`_get_dct8_basis_scale`, a captured forward builds them inside the graph and leaves the cache alone,
+ and the cache is filled outside inference mode, so that later calls in which autograd tracks the input can use it.
+ """
+ if is_compiling():
+ return _get_default_qt_y(device, dtype), _get_default_qt_c(device, dtype)
+ key = (dtype, device)
+ if key not in _DEFAULT_QT_CACHE:
+ with torch.inference_mode(False):
+ tables = (_get_default_qt_y(device, dtype), _get_default_qt_c(device, dtype))
+ if tables[0].is_cuda:
+ # The cache is read from every stream, and the tables are filled on this one: wait for them once, so that
+ # a call on another stream cannot read them before they are written.
+ torch.cuda.current_stream(tables[0].device).synchronize()
+ _DEFAULT_QT_CACHE[key] = tables
+ return _DEFAULT_QT_CACHE[key]
+
+
def _patchify_8x8(input: torch.Tensor) -> torch.Tensor:
"""Extract non-overlapping 8 x 8 patches from the given input image.
@@ -205,8 +236,9 @@ def _idct_8x8(input: torch.Tensor) -> torch.Tensor:
freq_idx = idx.unsqueeze(1)
basis = torch.cos((2.0 * spatial_idx + 1.0) * freq_idx * math.pi / 16.0)
- alpha = torch.ones(8, dtype=dtype, device=device)
- alpha[0] = 1.0 / (2**0.5)
+ # Built on the device in one go: assigning a Python float to an element copies it from the host, which waits
+ # for every queued kernel.
+ alpha = _device_literal([1.0 / (2**0.5)] + [1.0] * 7, dtype=dtype, device=device)
dct_scale = torch.outer(alpha, alpha)
input = input * dct_scale
@@ -589,8 +621,10 @@ def jpeg_codec_differentiable(
dtype: torch.dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
input = input.to(dtype)
# Use default QT if QT is not given
- quantization_table_y = _get_default_qt_y(device, dtype) if quantization_table_y is None else quantization_table_y
- quantization_table_c = _get_default_qt_c(device, dtype) if quantization_table_c is None else quantization_table_c
+ if quantization_table_y is None or quantization_table_c is None:
+ default_y, default_c = _default_quantization_tables(device, dtype)
+ quantization_table_y = default_y if quantization_table_y is None else quantization_table_y
+ quantization_table_c = default_c if quantization_table_c is None else quantization_table_c
KORNIA_CHECK_IS_TENSOR(quantization_table_y)
KORNIA_CHECK_IS_TENSOR(quantization_table_c)
# Check shape of inputs
@@ -634,10 +668,10 @@ def jpeg_codec_differentiable(
jpeg_quality, input, allow_one=True, msg="jpeg_quality needs one quality per image, or one for all."
)
# keep jpeg_quality same device as input torch.Tensor
- jpeg_quality = jpeg_quality.to(device, dtype)
+ jpeg_quality = _to_device_nonblocking(jpeg_quality, device, dtype)
# Quantization tables to same device and dtype as input image
- quantization_table_y = quantization_table_y.to(device, dtype)
- quantization_table_c = quantization_table_c.to(device, dtype)
+ quantization_table_y = _to_device_nonblocking(quantization_table_y, device, dtype)
+ quantization_table_c = _to_device_nonblocking(quantization_table_c, device, dtype)
# Perform encoding
y_encoded, cb_encoded, cr_encoded = _jpeg_encode(
image_rgb=input,
@@ -674,7 +708,11 @@ def _get_dct8_basis_scale(
# Build outside inference mode: an inference tensor in the cache would make later calls in which autograd
# tracks the input fail, since autograd cannot save it for backward.
with torch.inference_mode(False):
- _DCT8_CACHE[key] = _build_dct8_basis_scale(dtype, device)
+ basis = _build_dct8_basis_scale(dtype, device)
+ if basis[0].is_cuda:
+ # Read from every stream: wait once for the kernels that build it, as for the quantization tables.
+ torch.cuda.current_stream(basis[0].device).synchronize()
+ _DCT8_CACHE[key] = basis
return _DCT8_CACHE[key]
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index a9467f887..2597b0646 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -22,6 +22,8 @@ from typing import List, Tuple, Union
import torch
from torch import nn
+from kornia.core.utils import _as_tensor_nonblocking
+
__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]
@@ -203,8 +205,8 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
if std.shape and std.shape[0] != 1 and std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
- mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)
- std = torch.as_tensor(std, device=data.device, dtype=data.dtype)
+ mean = _as_tensor_nonblocking(mean, data.device, data.dtype)
+ std = _as_tensor_nonblocking(std, data.device, data.dtype)
mean = mean[..., None]
std = std[..., None]
@@ -374,8 +376,8 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
if std.shape and std.shape[0] != 1 and std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
- mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)
- std = torch.as_tensor(std, device=data.device, dtype=data.dtype)
+ mean = _as_tensor_nonblocking(mean, data.device, data.dtype)
+ std = _as_tensor_nonblocking(std, data.device, data.dtype)
if mean.dim() == 1:
mean = mean.view(1, -1, *([1] * (data.dim() - 2)))
diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.py
index 720f40c32..e91b3d79a 100644
--- a/kornia/enhance/shift_rgb.py
+++ b/kornia/enhance/shift_rgb.py
@@ -19,6 +19,7 @@
import torch
from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _to_device_nonblocking
from kornia.enhance.adjust import _check_floating_image
@@ -39,4 +40,5 @@ def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor,
shifts = [r_shift, g_shift, b_shift]
- return (image + torch.stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1)
+ shift = _to_device_nonblocking(torch.stack(shifts, dim=1).view(-1, 3, 1, 1), image.device, image.dtype)
+ return (image + shift).clamp_(min=0, max=1)
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 53a944fdc..2c2651796 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -21,6 +21,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _to_device_nonblocking
from kornia.filters.kernels import normalize_kernel2d
_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}
@@ -168,9 +169,9 @@ def filter2d(
# prepare kernel
b, c, h, w = input.shape
if behaviour == "conv":
- tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel.flip((-2, -1))[:, None, ...], input.device, input.dtype)
else:
- tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel[:, None, ...], input.device, input.dtype)
if normalized:
tmp_kernel = normalize_kernel2d(tmp_kernel)
@@ -360,9 +361,9 @@ def filter3d(
# prepare kernel
b, c, d, h, w = input.shape
if behaviour == "conv":
- tmp_kernel = kernel.flip((-3, -2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel.flip((-3, -2, -1))[:, None, ...], input.device, input.dtype)
else:
- tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel[:, None, ...], input.device, input.dtype)
if normalized:
bk, dk, hk, wk = kernel.shape
@@ -509,9 +510,9 @@ def fft_conv(
)
if behaviour == "conv":
- tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel.flip((-2, -1))[:, None, ...], input.device, input.dtype)
else:
- tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
+ tmp_kernel = _to_device_nonblocking(kernel[:, None, ...], input.device, input.dtype)
if normalized:
tmp_kernel = normalize_kernel2d(tmp_kernel)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 9feba6054..c022f6e6e 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -22,7 +22,8 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
-from kornia.core.utils import is_autocast_enabled, is_compiling
+from kornia.core.ops import _device_literal
+from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_compiling
from .filter import _to_floating, filter2d, filter2d_separable
from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
@@ -158,11 +159,22 @@ def gaussian_blur2d(
# promote before casting sigma and the kernel to the input's dtype, where an integer dtype truncates them (#5155)
input = _to_floating(input)
- if isinstance(sigma, tuple):
+ # The positivity check below reads ``host_sigma``: the Python numbers, or ``sigma`` in the input dtype on the
+ # device it came on, so that a CPU sigma, as the augmentations pass it, is checked without reading the GPU.
+ host_sigma: tuple[float, float] | torch.Tensor
+ if isinstance(sigma, tuple) and all(isinstance(s, (int, float)) for s in sigma):
+ host_sigma = sigma
+ # Filled on the device: ``torch.tensor(..., device=cuda)`` copies from the host and waits for every queued
+ # kernel. The values round from the same Python numbers either way.
+ sigma = _device_literal([sigma], device=input.device, dtype=input.dtype)
+ elif isinstance(sigma, tuple):
sigma = torch.tensor([sigma], device=input.device, dtype=input.dtype)
+ host_sigma = sigma
else:
KORNIA_CHECK_IS_TENSOR(sigma)
- sigma = sigma.to(device=input.device, dtype=input.dtype)
+ # Cast where it lives and then move: the blocking ``sigma.to(device, dtype)`` also casts on the host.
+ host_sigma = sigma.to(dtype=input.dtype)
+ sigma = _to_device_nonblocking(host_sigma, input.device)
KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
KORNIA_CHECK_SAME_SIZE(sigma, input, allow_one=True, msg="sigma must have a batch of 1 or the input batch.")
@@ -171,7 +183,10 @@ def gaussian_blur2d(
# Only interpolate `sigma` into the message when the check actually fails: a plain
# f-string here would format the whole `sigma` tensor (a costly tensor->str) on every
# eager call even when it passes β€” which dominated the eager Gaussian-blur runtime.
- positive = bool((sigma > 0).all())
+ if not isinstance(host_sigma, torch.Tensor):
+ # The same rounding to the input dtype as the device tensor, on the host.
+ host_sigma = torch.tensor([host_sigma], dtype=input.dtype)
+ positive = bool((host_sigma > 0).all())
KORNIA_CHECK(positive, "sigma must be positive" if positive else f"sigma must be positive, got {sigma}")
if separable:
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index f76ed94dc..08f3a50af 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -23,6 +23,7 @@ from typing import Optional, Union
import torch
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.ops import _device_literal
def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False) -> None:
@@ -183,7 +184,8 @@ def gaussian(
mean = float(window_size // 2) if mean is None else mean
if isinstance(mean, (int, float)):
- mean = torch.tensor([[float(mean)]], device=sigma.device, dtype=sigma.dtype)
+ # Filled on the device in eager mode, so a CUDA ``sigma`` gets no host copy that waits for queued work.
+ mean = _device_literal([[float(mean)]], device=sigma.device, dtype=sigma.dtype)
KORNIA_CHECK_IS_TENSOR(mean)
KORNIA_CHECK_SHAPE(mean, ["B", "1"])
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index e27114675..7094cc416 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -95,10 +95,21 @@ def _boxes_to_polygons(
return polygons
-def _validate_box_coordinates(boxes: torch.Tensor) -> None:
- """Validate that box coordinates are finite."""
- if not torch.isfinite(boxes).all():
+def _validate_box_values(boxes: torch.Tensor, width: torch.Tensor, height: torch.Tensor) -> None:
+ """Raise the first of the non-finite, width and height errors, reading all three checks in one host transfer.
+
+ The three reductions run on the device of ``boxes`` and come back together, so a CUDA box costs one device
+ synchronization instead of three. The errors, their messages and their order are those of the separate checks.
+ """
+ non_finite, bad_width, bad_height = torch.stack(
+ ((~torch.isfinite(boxes)).any(), (width <= 0).any(), (height <= 0).any())
+ ).tolist()
+ if non_finite:
raise ValueError("Some boxes have non-finite coordinates.")
+ if bad_width:
+ raise ValueError("Some boxes have negative widths or 0.")
+ if bad_height:
+ raise ValueError("Some boxes have negative heights or 0.")
def _assert_finite_vertices(boxes: torch.Tensor) -> None:
@@ -134,11 +145,9 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b
# Value validation reads the data, which graph capture cannot do; skip it under export. The vertex modes check
# finiteness asynchronously so that they stay fullgraph-compilable.
- if validate_boxes and not is_exporting() and boxes.numel() > 0:
- if mode.startswith("vertices"):
- _assert_finite_vertices(boxes)
- else:
- _validate_box_coordinates(boxes)
+ # The coordinate modes check finiteness together with the extents below, in one host read.
+ if validate_boxes and not is_exporting() and boxes.numel() > 0 and mode.startswith("vertices"):
+ _assert_finite_vertices(boxes)
if mode.startswith("vertices"):
if mode == "vertices":
@@ -166,10 +175,7 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b
# Value validation reads the data, which graph capture cannot do; skip it under export.
if validate_boxes and not is_exporting():
- if (width <= 0).any():
- raise ValueError("Some boxes have negative widths or 0.")
- if (height <= 0).any():
- raise ValueError("Some boxes have negative heights or 0.")
+ _validate_box_values(boxes, width, height)
xmin, ymin = boxes[..., 0], boxes[..., 1]
quadrilaterals = _boxes_to_polygons(xmin, ymin, width, height)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 3f3ff18ee..bc440cdd6 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -27,6 +27,7 @@ import torch.nn.functional as F
from kornia.core._compat import deprecated
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, ShapeError, are_checks_enabled
from kornia.core.exceptions import TypeCheckError
+from kornia.core.ops import _constant_tensor
from kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, is_compiling
__all__ = [
@@ -2055,7 +2056,13 @@ def normal_transform_pixel(
torch.stack([zero, zero, anchor]),
]
)
+ elif dtype is None or dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):
+ # Filled on the device: ``torch.tensor(..., device=cuda)`` copies from the host and waits for every
+ # queued kernel before it returns. The values round from the same doubles to ``dtype`` either way.
+ tr_mat = _constant_tensor([[sx, 0.0, tx], [0.0, sy, ty], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
else:
+ # Complex and float8 dtypes keep the host literal: ``torch.full`` has no float8 fill on torch 2.5.1 (CPU)
+ # or on MPS.
tr_mat = torch.tensor([[sx, 0.0, tx], [0.0, sy, ty], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
else:
# Low-precision floating types cannot represent every practical image size exactly
@@ -2197,7 +2204,15 @@ def normal_transform_pixel3d(
torch.stack([zero, zero, zero, anchor]),
]
)
+ elif dtype is None or dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):
+ # As in 2-D: filled on the device, without a host copy that waits for the queue.
+ tr_mat = _constant_tensor(
+ [[sx, 0.0, 0.0, tx], [0.0, sy, 0.0, ty], [0.0, 0.0, sz, tz], [0.0, 0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ )
else:
+ # As in 2-D: complex and float8 dtypes keep the host literal.
tr_mat = torch.tensor(
[[sx, 0.0, 0.0, tx], [0.0, sy, 0.0, ty], [0.0, 0.0, sz, tz], [0.0, 0.0, 0.0, 1.0]],
device=device,
@@ -2235,6 +2250,11 @@ def normal_transform_pixel3d(
return tr_mat.unsqueeze(0) # 1x4x4
+def _is_floating_or_complex(x: torch.Tensor) -> bool:
+ """Whether ``x`` has a floating or complex dtype, the only dtypes in which a pixel normalization is invertible."""
+ return x.is_floating_point() or x.is_complex()
+
+
def denormalize_homography(
dst_pix_trans_src_pix: torch.Tensor,
dsize_src: tuple[int, int],
@@ -2303,7 +2323,12 @@ def denormalize_homography(
dtype=normalization_dtype,
align_corners=align_corners,
).to(dst_pix_trans_src_pix)
- dst_denorm_trans_dst_pix = _torch_inverse_cast(dst_norm_trans_dst_pix)
+ # A floating pixel normalization is triangular with diagonal scales 2 / (size - 1), so it is invertible unless a
+ # scale underflows to 0, which in float16 takes an axis longer than 2**26 pixels; that matrix gives non-finite
+ # values instead of an error. An integer one truncates its scales to 0 (kornia#3959) and keeps the error check.
+ dst_denorm_trans_dst_pix = _torch_inverse_cast(
+ dst_norm_trans_dst_pix, check_errors=not _is_floating_or_complex(dst_norm_trans_dst_pix)
+ )
# compute chain transformations
dst_norm_trans_src_norm: torch.Tensor = dst_denorm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)
return dst_norm_trans_src_norm
@@ -2372,7 +2397,11 @@ def normalize_homography3d(
src_d, src_h, src_w, device=dst_pix_trans_src_pix.device, dtype=normalization_dtype
).to(dst_pix_trans_src_pix)
- src_pix_trans_src_norm = _torch_inverse_cast(src_norm_trans_src_pix)
+ # A floating pixel normalization is invertible unless a scale underflows (see `denormalize_homography`); an
+ # integer one keeps the error check (kornia#3959).
+ src_pix_trans_src_norm = _torch_inverse_cast(
+ src_norm_trans_src_pix, check_errors=not _is_floating_or_complex(src_norm_trans_src_pix)
+ )
dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(
dst_d, dst_h, dst_w, device=dst_pix_trans_src_pix.device, dtype=normalization_dtype
).to(dst_pix_trans_src_pix)
@@ -2455,7 +2484,11 @@ def denormalize_homography3d(
dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(
dst_d, dst_h, dst_w, device=dst_pix_trans_src_pix.device, dtype=normalization_dtype
).to(dst_pix_trans_src_pix)
- dst_pix_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_dst_pix)
+ # A floating pixel normalization is invertible unless a scale underflows (see `denormalize_homography`); an
+ # integer one keeps the error check (kornia#3959).
+ dst_pix_trans_dst_norm = _torch_inverse_cast(
+ dst_norm_trans_dst_pix, check_errors=not _is_floating_or_complex(dst_norm_trans_dst_pix)
+ )
# compute chain transformations
return dst_pix_trans_dst_norm @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 04dde9dae..d38fa6f6c 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -21,7 +21,7 @@ from typing import Optional, Tuple, Union
import torch
from torch import nn
-from kornia.core.ops import eye_like
+from kornia.core.ops import _device_literal, eye_like
from kornia.core.utils import _extract_device_dtype
from kornia.filters import gaussian_blur2d
@@ -67,8 +67,11 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
height, width = tensor.shape[-2:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
- center: torch.Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
- return center
+ # Filled on the device in eager mode: ``torch.tensor(..., device=cuda)`` copies from the host and waits for queued
+ # kernels. TorchScript, which cannot compile ``_device_literal``, keeps the host literal.
+ if torch.jit.is_scripting():
+ return torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
+ return _device_literal([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
@@ -79,8 +82,10 @@ def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
center_z: float = float(depth - 1) / 2
- center: torch.Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
- return center
+ # Filled on the device in eager mode, as in ``_compute_tensor_center``.
+ if torch.jit.is_scripting():
+ return torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
+ return _device_literal([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
def _compute_rotation_matrix(angle: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index f19d15822..d882b50b2 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -514,7 +514,10 @@ def crop_by_indices(
KORNIA_CHECK_SHAPE(src_box, ["B", "4", "2"])
B, C, _, _ = input_tensor.shape
- src = torch.as_tensor(src_box, device=input_tensor.device, dtype=torch.long)
+ # Kept on the device ``src_box`` lives on: the coordinates are read back to Python below, which costs no device
+ # synchronization for the CPU boxes the augmentations pass. A float box truncates to the same integers either way:
+ # the former copy to a CUDA input's device also cast on the host.
+ src = torch.as_tensor(src_box, dtype=torch.long)
x1 = src[:, 0, 0]
x2 = src[:, 1, 0] + 1
y1 = src[:, 0, 1]
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 9d04a7637..89ad44fa0 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -21,6 +21,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.ops import _device_literal
from kornia.core.utils import _torch_grid_sample
from kornia.filters import filter2d_separable
from kornia.filters.kernels import get_gaussian_kernel1d
@@ -97,8 +98,12 @@ def elastic_transform2d(
device, dtype = image.device, image.dtype
# Normalise sigma to a (B, 2) = (sigma_y, sigma_x) tensor, matching get_gaussian_kernel2d.
+ # Python numbers are filled on the device: ``torch.tensor(..., device=cuda)`` copies from the host and waits for
+ # every queued kernel. The values round from the same numbers either way.
if isinstance(sigma, torch.Tensor):
sigma = sigma.expand(2)[None, ...]
+ elif all(isinstance(s, (int, float)) for s in sigma):
+ sigma = _device_literal([sigma], device=device, dtype=dtype)
else:
sigma = torch.tensor([sigma], device=device, dtype=dtype)
ksize_y, ksize_x = kernel_size
@@ -113,6 +118,9 @@ def elastic_transform2d(
if isinstance(alpha, torch.Tensor):
alpha_x = alpha[0]
alpha_y = alpha[1]
+ elif all(isinstance(a, (int, float)) for a in alpha):
+ alpha_x = _device_literal(alpha[0], device=device, dtype=dtype)
+ alpha_y = _device_literal(alpha[1], device=device, dtype=dtype)
else:
alpha_x = torch.tensor(alpha[0], device=device, dtype=dtype)
alpha_y = torch.tensor(alpha[1], device=device, dtype=dtype)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index f6954dea8..0d340d4e4 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -1524,7 +1524,8 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
from_origin_mat[..., :3, -1] += center
to_origin_mat = from_origin_mat.clone()
- to_origin_mat = _torch_inverse_cast(from_origin_mat)
+ # An identity plus a translation column is unit triangular, so it is always invertible.
+ to_origin_mat = _torch_inverse_cast(from_origin_mat, check_errors=False)
# append translation with torch.zeros
proj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4
@@ -1999,7 +2000,8 @@ def homography_warp3d(
# ``create_meshgrid3d`` follows kornia's ``(d, x, y)`` convention, which
# ``normalize_pixel_coordinates3d`` and ``conv_soft_argmax3d`` rely on. ``warp_grid3d`` and
# ``grid_sample`` both read the last axis as ``(x, y, z)``, so the depth channel moves last.
- grid = grid[..., [1, 2, 0]]
+ # Stacked rather than indexed with a list, which is copied to the device with a blocking transfer.
+ grid = torch.stack((grid[..., 1], grid[..., 2], grid[..., 0]), -1)
warped_grid = warp_grid3d(grid, src_homo_dst)
return _torch_grid_sample(
diff --git a/testing/augmentation/sync_registry.py b/testing/augmentation/sync_registry.py
new file mode 100644
index 000000000..599693912
--- /dev/null
+++ b/testing/augmentation/sync_registry.py
@@ -0,0 +1,537 @@
+# 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.
+#
+
+"""Registry of augmentation calls whose CUDA host synchronizations are counted.
+
+Every public augmentation, container, automatic policy and preset is listed here with explicit constructor
+arguments, together with the public functions in which a host synchronization was found. ``make_call`` builds
+the inputs and returns a closure that runs one case, so a caller can warm it up and then count what it
+synchronizes with ``sync_sites``. The CUDA guard in ``tests/augmentation/test_host_sync.py`` and the
+byte-identity snapshots both read this file, so it uses only kornia's public API and torch.
+"""
+
+from __future__ import annotations
+
+import collections
+import dataclasses
+import functools
+import os
+import traceback
+import warnings
+from typing import Any, Callable
+
+import torch
+
+import kornia
+import kornia.augmentation as K
+from kornia.augmentation import auto as KAuto
+from kornia.augmentation.presets.ada import AdaptiveDiscriminatorAugmentation
+
+__all__ = ["AUG_CASES", "EXCLUDED", "INHERENT_SITES", "PASS_THROUGH", "AugCase", "make_call", "sync_sites"]
+
+# The message torch emits for every synchronizing call under ``torch.cuda.set_sync_debug_mode("warn")``.
+_SYNC_MESSAGE = "called a synchronizing CUDA operation"
+
+ALL_2D = ("forward", "seq_annotations", "p_half")
+GEOMETRIC_2D = ("forward", "inverse", "seq_annotations", "seq_inverse", "p_half")
+FORWARD_P = ("forward", "p_half")
+
+
[email protected](frozen=True)
+class AugCase:
+ """One registered augmentation, container, policy or function.
+
+ Attributes:
+ name: Public name, used in the test ids.
+ build: Zero-argument factory. For augmentations it is a ``functools.partial`` of the class, so the
+ ``p_half`` case can rebuild it with ``p=0.5``. For ``"functional"`` entries it returns a function
+ that takes the 2D input and returns the closure to run.
+ kind: One of ``"2d"``, ``"3d"``, ``"mix"``, ``"container"``, ``"auto"`` and ``"functional"``.
+ cases: The calls to make, a subset of ``"forward"``, ``"inverse"``, ``"seq_annotations"``,
+ ``"seq_inverse"`` and ``"p_half"``.
+ inputs: The 2D inputs a ``forward`` or ``p_half`` call passes, by name: ``"input"``, ``"labels"`` (an
+ integer label mask) or ``"class"`` (one class label per sample).
+ """
+
+ name: str
+ build: Callable[[], Any]
+ kind: str
+ cases: tuple[str, ...]
+ inputs: tuple[str, ...] = ("input",)
+
+
+def _aug(cls: type, *args: Any, kind: str = "2d", cases: tuple[str, ...] = ALL_2D, **kwargs: Any) -> AugCase:
+ return AugCase(cls.__name__, functools.partial(cls, *args, **kwargs), kind, cases)
+
+
+def _functional(name: str, setup: Callable[[torch.Tensor], Callable[[], Any]]) -> AugCase:
+ return AugCase(name, lambda: setup, "functional", ("forward",))
+
+
+def _setup_rotate(x: torch.Tensor) -> Callable[[], Any]:
+ angle = torch.linspace(-30.0, 30.0, x.shape[0], device=x.device, dtype=x.dtype)
+ return lambda: kornia.geometry.transform.rotate(x, angle)
+
+
+def _setup_elastic(x: torch.Tensor) -> Callable[[], Any]:
+ noise = torch.rand(x.shape[0], 2, *x.shape[-2:], device=x.device, dtype=x.dtype) * 2 - 1
+ return lambda: kornia.geometry.transform.elastic_transform2d(x, noise)
+
+
+def _setup_jpeg(x: torch.Tensor) -> Callable[[], Any]:
+ # A CPU quality, as RandomJPEG passes: the range check of a CUDA quality reads it back on the host.
+ quality = torch.linspace(50.0, 90.0, x.shape[0], dtype=x.dtype)
+ return lambda: kornia.enhance.jpeg_codec_differentiable(x, quality)
+
+
+def _setup_crop_by_indices(x: torch.Tensor) -> Callable[[], Any]:
+ # Augmentations pass boxes sampled on the CPU, so the functional entry does too.
+ boxes = torch.tensor([[[2, 3], [17, 3], [17, 18], [2, 18]]], dtype=torch.long).repeat(x.shape[0], 1, 1)
+ return lambda: kornia.geometry.transform.crop_by_indices(x, boxes, size=(16, 16))
+
+
+FUNCTIONAL_CASES = [
+ _functional(
+ "normal_transform_pixel",
+ lambda x: lambda: kornia.geometry.conversions.normal_transform_pixel(32, 32, device=x.device, dtype=x.dtype),
+ ),
+ _functional(
+ "normal_transform_pixel3d",
+ lambda x: (
+ lambda: kornia.geometry.conversions.normal_transform_pixel3d(8, 16, 16, device=x.device, dtype=x.dtype)
+ ),
+ ),
+ _functional(
+ "get_gaussian_kernel1d",
+ lambda x: functools.partial(
+ kornia.filters.get_gaussian_kernel1d,
+ 5,
+ torch.full((x.shape[0], 1), 1.5, device=x.device, dtype=x.dtype),
+ ),
+ ),
+ _functional("rgb_to_grayscale", lambda x: functools.partial(kornia.color.rgb_to_grayscale, x)),
+ _functional(
+ "rgb_to_grayscale[rgb_weights]",
+ lambda x: functools.partial(kornia.color.rgb_to_grayscale, x, torch.tensor([0.2, 0.3, 0.5], dtype=x.dtype)),
+ ),
+ _functional("rgb_to_hls", lambda x: functools.partial(kornia.color.rgb_to_hls, x)),
+ _functional("hls_to_rgb", lambda x: functools.partial(kornia.color.hls_to_rgb, x)),
+ _functional("rotate", _setup_rotate),
+ _functional("elastic_transform2d", _setup_elastic),
+ _functional("sharpness", lambda x: functools.partial(kornia.enhance.sharpness, x, 0.5)),
+ _functional("jpeg_codec_differentiable", _setup_jpeg),
+ _functional("gaussian_blur2d", lambda x: functools.partial(kornia.filters.gaussian_blur2d, x, (5, 5), (1.5, 1.5))),
+ _functional("crop_by_indices", _setup_crop_by_indices),
+]
+
+
+def _intensity_cases() -> list[AugCase]:
+ return [
+ _aug(K.ColorJiggle, 0.1, 0.1, 0.1, 0.1, p=1.0),
+ _aug(K.ColorJitter, 0.1, 0.1, 0.1, 0.1, p=1.0),
+ # A fixed order takes the branch-free dispatch that torch.compile traces (benchmarks/augmentation/pipeline.py).
+ AugCase(
+ "ColorJiggle[order]",
+ functools.partial(K.ColorJiggle, 0.1, 0.1, 0.1, 0.1, p=1.0, order=[0, 1, 2, 3]),
+ "2d",
+ ALL_2D,
+ ),
+ AugCase(
+ "ColorJitter[order]",
+ functools.partial(K.ColorJitter, 0.1, 0.1, 0.1, 0.1, p=1.0, order=[0, 1, 2, 3]),
+ "2d",
+ ALL_2D,
+ ),
+ _aug(K.Denormalize, mean=(0.5, 0.4, 0.3), std=(0.2, 0.25, 0.3)),
+ _aug(K.Normalize, mean=(0.5, 0.4, 0.3), std=(0.2, 0.25, 0.3)),
+ _aug(K.RandomAutoContrast, p=1.0),
+ _aug(K.RandomBoxBlur, p=1.0),
+ _aug(K.RandomBrightness, brightness=(0.8, 1.2), p=1.0),
+ _aug(K.RandomChannelDropout, p=1.0),
+ _aug(K.RandomChannelShuffle, p=1.0),
+ _aug(K.RandomClahe, p=1.0),
+ _aug(K.RandomContrast, contrast=(0.8, 1.2), p=1.0),
+ _aug(K.RandomEqualize, p=1.0),
+ _aug(K.RandomErasing, p=1.0),
+ _aug(K.RandomGamma, gamma=(0.8, 1.2), gain=(0.9, 1.1), p=1.0),
+ _aug(K.RandomGaussianBlur, (5, 5), (0.1, 2.0), p=1.0),
+ _aug(K.RandomGaussianIllumination, p=1.0),
+ _aug(K.RandomGaussianNoise, std=0.1, p=1.0),
+ _aug(K.RandomGrayscale, p=1.0),
+ AugCase(
+ "RandomGrayscale[rgb_weights]",
+ functools.partial(K.RandomGrayscale, rgb_weights=torch.tensor([0.2, 0.3, 0.5]), p=1.0),
+ "2d",
+ ALL_2D,
+ ),
+ _aug(K.RandomHue, hue=(-0.1, 0.1), p=1.0),
+ _aug(K.RandomInvert, p=1.0),
+ _aug(K.RandomJPEG, jpeg_quality=(50.0, 90.0), p=1.0),
+ _aug(K.RandomLinearCornerIllumination, p=1.0),
+ _aug(K.RandomLinearIllumination, p=1.0),
+ _aug(K.RandomMedianBlur, p=1.0),
+ _aug(K.RandomMotionBlur, 3, 35.0, 0.5, p=1.0),
+ _aug(K.RandomPlanckianJitter, p=1.0),
+ _aug(K.RandomPlasmaBrightness, p=1.0),
+ _aug(K.RandomPlasmaContrast, p=1.0),
+ _aug(K.RandomPlasmaShadow, p=1.0),
+ _aug(K.RandomPosterize, p=1.0),
+ _aug(K.RandomRGBShift, p=1.0),
+ _aug(K.RandomRain, p=1.0),
+ _aug(K.RandomSaltAndPepperNoise, p=1.0),
+ _aug(K.RandomSaturation, saturation=(0.8, 1.2), p=1.0),
+ _aug(K.RandomSharpness, p=1.0),
+ _aug(K.RandomSnow, p=1.0),
+ _aug(K.RandomSolarize, p=1.0),
+ ]
+
+
+def _geometric_cases() -> list[AugCase]:
+ fisheye = {
+ "center_x": torch.tensor([-0.3, 0.3]),
+ "center_y": torch.tensor([-0.3, 0.3]),
+ "gamma": torch.tensor([0.9, 1.0]),
+ }
+ return [
+ _aug(K.CenterCrop, 16),
+ _aug(K.LongestMaxSize, 24),
+ _aug(K.PadTo, (40, 40), cases=("forward", "inverse", "seq_annotations", "seq_inverse")),
+ _aug(K.RandomAffine, 15.0, translate=(0.1, 0.1), scale=(0.9, 1.1), shear=10.0, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomCrop, (16, 16), p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomElasticTransform, p=1.0),
+ _aug(K.RandomFisheye, **fisheye, p=1.0, cases=FORWARD_P),
+ _aug(K.RandomHorizontalFlip, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomPerspective, 0.5, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomResizedCrop, (16, 16), p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomRotation, 30.0, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomRotation90, (0, 3), p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomShear, 10.0, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomThinPlateSpline, p=1.0, cases=FORWARD_P),
+ _aug(K.RandomTranslate, (-0.1, 0.1), (-0.1, 0.1), p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.RandomVerticalFlip, p=1.0, cases=GEOMETRIC_2D),
+ _aug(K.Resize, (24, 24), cases=GEOMETRIC_2D),
+ AugCase(
+ "Resize[align_corners=False]",
+ functools.partial(K.Resize, (24, 24), align_corners=False),
+ "2d",
+ GEOMETRIC_2D,
+ ),
+ AugCase("Resize[nearest]", functools.partial(K.Resize, (24, 24), resample="nearest"), "2d", GEOMETRIC_2D),
+ _aug(K.SmallestMaxSize, 24, cases=GEOMETRIC_2D),
+ ]
+
+
+def _mix_cases() -> list[AugCase]:
+ return [
+ _aug(K.PatchMix, patch_size=8, p=1.0, kind="mix", cases=FORWARD_P),
+ _aug(K.RandomCutMixV2, p=1.0, use_correct_lambda=True, kind="mix", cases=FORWARD_P),
+ AugCase(
+ "RandomCutMixV2[class]",
+ functools.partial(K.RandomCutMixV2, p=1.0, use_correct_lambda=True, data_keys=["input", "class"]),
+ "mix",
+ FORWARD_P,
+ ("input", "class"),
+ ),
+ _aug(K.RandomJigsaw, (4, 4), p=1.0, kind="mix", cases=FORWARD_P),
+ _aug(K.RandomMixUpV2, p=1.0, kind="mix", cases=FORWARD_P),
+ AugCase(
+ "RandomMixUpV2[class]",
+ functools.partial(K.RandomMixUpV2, p=1.0, data_keys=["input", "class"]),
+ "mix",
+ FORWARD_P,
+ ("input", "class"),
+ ),
+ _aug(K.RandomMosaic, (32, 32), p=1.0, kind="mix", cases=FORWARD_P),
+ AugCase(
+ "RandomMosaic[resample]",
+ functools.partial(K.RandomMosaic, (32, 32), p=1.0, cropping_mode="resample"),
+ "mix",
+ FORWARD_P,
+ ),
+ _aug(K.RandomTransplantation, p=1.0, kind="mix", cases=FORWARD_P),
+ ]
+
+
+def _cases_3d() -> list[AugCase]:
+ return [
+ _aug(K.CenterCrop3D, (4, 8, 8), kind="3d", cases=FORWARD_P),
+ _aug(K.RandomAffine3D, 15.0, translate=(0.1, 0.1, 0.1), scale=(0.9, 1.1), p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomCrop3D, (4, 8, 8), p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomDepthicalFlip3D, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomEqualize3D, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomHorizontalFlip3D, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomMotionBlur3D, 3, 35.0, 0.5, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomPerspective3D, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomRotation3D, 15.0, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomTransplantation3D, p=1.0, kind="3d", cases=FORWARD_P),
+ _aug(K.RandomVerticalFlip3D, p=1.0, kind="3d", cases=FORWARD_P),
+ ]
+
+
+def _pipeline() -> list[torch.nn.Module]:
+ return [
+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomAffine(15.0, translate=(0.1, 0.1), p=1.0),
+ K.RandomHorizontalFlip(p=0.5),
+ ]
+
+
+def _container_cases() -> list[AugCase]:
+ def augmentation_sequential() -> K.AugmentationSequential:
+ return K.AugmentationSequential(*_pipeline())
+
+ def image_sequential() -> K.ImageSequential:
+ return K.ImageSequential(*_pipeline(), random_apply=2)
+
+ def video_sequential() -> K.VideoSequential:
+ return K.VideoSequential(*_pipeline(), data_format="BCTHW", same_on_frame=True)
+
+ def patch_sequential() -> K.PatchSequential:
+ return K.PatchSequential(
+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomAffine(15.0, p=1.0),
+ grid_size=(2, 2),
+ patchwise_apply=False,
+ )
+
+ def ada() -> AdaptiveDiscriminatorAugmentation:
+ return AdaptiveDiscriminatorAugmentation(initial_p=0.8)
+
+ return [
+ AugCase("AugmentationSequential", augmentation_sequential, "container", ("forward", "inverse")),
+ AugCase("ImageSequential", image_sequential, "container", ("forward",)),
+ AugCase("VideoSequential", video_sequential, "container", ("forward",)),
+ AugCase("PatchSequential", patch_sequential, "container", ("forward",)),
+ AugCase("AdaptiveDiscriminatorAugmentation", ada, "container", ("forward",)),
+ ]
+
+
+# Every operation the automatic policies draw from, each run on its own so that a fixed seed covers all of them.
+_AUTO_OPERATIONS = [
+ ("auto_contrast", 0, 1),
+ ("equalize", 0, 1),
+ ("invert", 0, 1),
+ ("rotate", -30.0, 30.0),
+ ("posterize", 4.0, 8.0),
+ ("solarize", 0.0, 1.0),
+ ("solarize_add", 0.0, 0.43),
+ ("color", 0.1, 1.9),
+ ("contrast", 0.1, 1.9),
+ ("brightness", 0.1, 1.9),
+ ("sharpness", 0.1, 1.9),
+ ("shear_x", -0.3, 0.3),
+ ("shear_y", -0.3, 0.3),
+ ("translate_x", -0.1, 0.1),
+ ("translate_y", -0.1, 0.1),
+]
+
+
+def _auto_cases() -> list[AugCase]:
+ cases = [
+ AugCase("AutoAugment", KAuto.AutoAugment, "auto", ("forward",)),
+ AugCase("RandAugment", functools.partial(KAuto.RandAugment, n=2, m=10), "auto", ("forward",)),
+ AugCase("TrivialAugment", KAuto.TrivialAugment, "auto", ("forward",)),
+ ]
+ for op in _AUTO_OPERATIONS:
+ build = functools.partial(KAuto.RandAugment, n=1, m=10, policy=[[op]])
+ cases.append(AugCase(f"RandAugment[{op[0]}]", build, "auto", ("forward",)))
+ return cases
+
+
+AUG_CASES: list[AugCase] = [
+ *_intensity_cases(),
+ *_geometric_cases(),
+ *_mix_cases(),
+ *_cases_3d(),
+ *_container_cases(),
+ *_auto_cases(),
+ *FUNCTIONAL_CASES,
+]
+
+EXCLUDED: dict[str, str] = {
+ "RandomDissolving": "downloads a Stable Diffusion model on first use",
+ "AugmentationBase2D": "abstract base",
+ "AugmentationBase3D": "abstract base",
+ "GeometricAugmentationBase2D": "abstract base",
+ "GeometricAugmentationBase3D": "abstract base",
+ "IntensityAugmentationBase2D": "abstract base",
+ "IntensityAugmentationBase3D": "abstract base",
+ "MixAugmentationBaseV2": "abstract base",
+ "RigidAffineAugmentationBase2D": "abstract base",
+ "RigidAffineAugmentationBase3D": "abstract base",
+}
+
+# ``"relpath.py:function"`` keys of the synchronizations that stay, each with the reason it is inherent.
+INHERENT_SITES: dict[str, str] = {
+ "geometry/boxes.py:_validate_box_values": (
+ "validation of user boxes: the non-finite, width and height errors read the box data on the host, in one "
+ "transfer for all three checks"
+ ),
+ "augmentation/_2d/mix/transplantation.py:params_from_input": (
+ "the transplanted labels are drawn from the values of the mask, which lives on the device (`unique` has a "
+ "data-dependent size)"
+ ),
+ "augmentation/presets/ada.py:forward": (
+ "ADA draws the augmented subset on the input's device and returns early when it is empty"
+ ),
+ "augmentation/presets/ada.py:_sample_inputs": (
+ "ADA augments the drawn subset only, whose size depends on the device draw (boolean indexing)"
+ ),
+ "augmentation/presets/ada.py:_merge_inputs": "ADA writes the augmented subset back by its device mask",
+ "geometry/transform/thin_plate_spline.py:get_tps_transform": (
+ "`torch.linalg.solve` checks the user-visible TPS system for singularity and raises (decision D1)"
+ ),
+ "augmentation/_2d/geometric/base.py:compute_inverse_transformation": (
+ "`inverse()` inverts the user-visible transformation matrix with `torch.linalg.inv`, which raises for a "
+ "singular matrix (decision D1)"
+ ),
+ "geometry/transform/imgwarp.py:warp_affine3d": (
+ "the public 3D warp inverts the caller's affine matrix with `torch.linalg.inv`, which raises for a singular "
+ "matrix (decision D1)"
+ ),
+ "geometry/transform/imgwarp.py:_transform_warp_impl3d": (
+ "`warp_perspective3d` inverts the caller's homography with `torch.linalg.inv`, which raises for a singular "
+ "matrix (decision D1)"
+ ),
+}
+
+# Thin wrappers whose synchronizations belong to their caller. A site is the deepest kornia frame that is not one of
+# them, so that INHERENT_SITES names the caller, which is what decides whether the synchronization is inherent.
+PASS_THROUGH: frozenset[str] = frozenset({"core/utils.py:_torch_inverse_cast", "core/utils.py:_torch_solve_cast"})
+
+
+def _inputs_2d(device: torch.device, dtype: torch.dtype) -> dict[str, torch.Tensor]:
+ boxes = torch.tensor([[[2.0, 3.0, 20.0, 25.0]]], device=device, dtype=dtype).repeat(4, 1, 1)
+ keypoints = torch.tensor([[[5.0, 6.0], [20.0, 21.0]]], device=device, dtype=dtype).repeat(4, 1, 1)
+ return {
+ "input": torch.rand(4, 3, 32, 32, device=device, dtype=dtype),
+ "mask": (torch.rand(4, 1, 32, 32, device=device) > 0.5).to(dtype),
+ "labels": torch.randint(0, 3, (4, 32, 32), device=device),
+ "class": torch.randint(0, 10, (4,), device=device),
+ "bbox_xyxy": boxes,
+ "keypoints": keypoints,
+ }
+
+
+def _inputs_3d(device: torch.device, dtype: torch.dtype) -> dict[str, torch.Tensor]:
+ return {
+ "input": torch.rand(2, 3, 8, 16, 16, device=device, dtype=dtype),
+ "labels": torch.randint(0, 3, (2, 8, 16, 16), device=device),
+ }
+
+
+def _build(case: AugCase, which: str) -> Any:
+ if which == "p_half":
+ build = case.build
+ if not isinstance(build, functools.partial):
+ raise ValueError(f"{case.name} has no constructor arguments to rebuild with p=0.5")
+ return functools.partial(build.func, *build.args, **{**build.keywords, "p": 0.5})()
+ return case.build()
+
+
+def make_call(case: AugCase, which: str, device: torch.device, dtype: torch.dtype) -> Callable[[], Any]:
+ """Build the module and inputs of ``case`` on ``device`` and return a closure that runs ``which``.
+
+ The closure carries the module it calls as its ``module`` attribute (``None`` for functions), so a caller
+ can read ``_params`` and ``transform_matrix`` after running it, and its input tensors by data key as its
+ ``inputs`` attribute, so a caller can make the image require gradients before running it.
+ """
+ if which not in case.cases:
+ raise ValueError(f"{case.name} does not register the case {which!r}")
+ module = _build(case, which)
+ fn: Callable[[], Any]
+ if case.kind == "functional":
+ data = _inputs_2d(device, dtype)
+ fn = module(data["input"])
+ fn.module = None # type: ignore[attr-defined]
+ fn.inputs = data # type: ignore[attr-defined]
+ return fn
+
+ if case.kind == "3d":
+ data = _inputs_3d(device, dtype)
+ x = data["input"]
+ if isinstance(module, K.RandomTransplantation3D):
+ labels = data["labels"]
+
+ def fn() -> Any:
+ return module(x, labels)
+ else:
+
+ def fn() -> Any:
+ return module(x)
+ elif case.kind == "container" and isinstance(module, K.VideoSequential):
+ data = {"input": torch.rand(2, 3, 4, 32, 32, device=device, dtype=dtype)}
+ x = data["input"]
+
+ def fn() -> Any:
+ return module(x)
+ else:
+ data = _inputs_2d(device, dtype)
+ x, mask, boxes, keypoints = data["input"], data["mask"], data["bbox_xyxy"], data["keypoints"]
+ if which in ("forward", "p_half"):
+ names = ("input", "labels") if isinstance(module, K.RandomTransplantation) else case.inputs
+ args = [data[name] for name in names]
+
+ def fn() -> Any:
+ return module(*args)
+ elif which == "inverse":
+
+ def fn() -> Any:
+ return module.inverse(module(x))
+ else:
+ seq = K.AugmentationSequential(module, data_keys=["input", "mask", "bbox_xyxy", "keypoints"])
+ if which == "seq_annotations":
+
+ def fn() -> Any:
+ return seq(x, mask, boxes, keypoints)
+ else:
+
+ def fn() -> Any:
+ return seq.inverse(*seq(x, mask, boxes, keypoints))
+
+ fn.module = module # type: ignore[attr-defined]
+ fn.inputs = data # type: ignore[attr-defined]
+ return fn
+
+
+def sync_sites(fn: Callable[[], Any]) -> collections.Counter[str]:
+ """Run ``fn`` under the CUDA sync debug mode and count its synchronizations by site.
+
+ A site is the deepest kornia frame on the stack that is not in ``PASS_THROUGH``, as ``"relpath.py:function"``
+ relative to the kornia package; a synchronization with no kornia frame on the stack counts as
+ ``"<outside kornia>"``. The debug mode is a prototype that misses some synchronizations, so a profiler count of
+ ``cudaStreamSynchronize`` is the cross-check. The mode is reset to ``0`` even when ``fn`` raises.
+ """
+ root = os.path.dirname(kornia.__file__) + os.sep
+ sites: collections.Counter[str] = collections.Counter()
+
+ def hook(message: Any, category: Any, filename: str, lineno: int, file: Any = None, line: Any = None) -> None:
+ if _SYNC_MESSAGE not in str(message):
+ return
+ keys = [f"{f.filename[len(root) :]}:{f.name}" for f in traceback.extract_stack() if f.filename.startswith(root)]
+ callers = [k for k in keys if k not in PASS_THROUGH]
+ sites[callers[-1] if callers else keys[-1] if keys else "<outside kornia>"] += 1
+
+ try:
+ torch.cuda.set_sync_debug_mode("warn")
+ with warnings.catch_warnings():
+ warnings.simplefilter("always")
+ warnings.showwarning = hook
+ fn()
+ finally:
+ torch.cuda.set_sync_debug_mode(0)
+ return sites
diff --git a/tests/augmentation/test_host_sync.py b/tests/augmentation/test_host_sync.py
new file mode 100644
index 000000000..4e5205c73
--- /dev/null
+++ b/tests/augmentation/test_host_sync.py
@@ -0,0 +1,255 @@
+# 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.
+#
+
+"""CUDA host-synchronization guard for every augmentation in ``testing.augmentation.sync_registry``."""
+
+from __future__ import annotations
+
+import inspect
+import json
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.augmentation import auto as KAuto
+from kornia.augmentation import container as KContainer
+from kornia.augmentation import presets as KPresets
+from kornia.augmentation.base import _BasicAugmentationBase
+from kornia.augmentation.container import ImageSequential
+from kornia.augmentation.presets import ada as KAda
+
+from testing.augmentation.sync_registry import AUG_CASES, EXCLUDED, INHERENT_SITES, make_call, sync_sites
+from testing.base import BaseTester
+
+_CALLS = [pytest.param(case, which, id=f"{case.name}-{which}") for case in AUG_CASES for which in case.cases]
+_HALF = (torch.float16, torch.bfloat16)
+
+# Augmentations whose stored ``_params`` are replayed, as given and moved to CUDA (Review Focus 1).
+_REPLAY = {
+ "RandomAffine": lambda: K.RandomAffine(15.0, translate=(0.1, 0.1), scale=(0.9, 1.1), shear=10.0, p=1.0),
+ "RandomBrightness": lambda: K.RandomBrightness(brightness=(0.8, 1.2), p=1.0),
+ "RandomCrop": lambda: K.RandomCrop((16, 16), p=1.0),
+ "RandomPerspective": lambda: K.RandomPerspective(0.5, p=1.0),
+}
+# One augmentation per gate (Review Focus 2): ``_blend_by_prob`` for an intensity and a geometric augmentation, the
+# matrix gates of 2D and 3D geometry, and the batch-level gate of the mix augmentations.
+_GATED = {
+ "RandomAffine": (lambda p, same: K.RandomAffine(30.0, p=p, same_on_batch=same), (8, 3, 16, 16)),
+ "RandomBrightness": (lambda p, same: K.RandomBrightness((0.5, 1.5), p=p, same_on_batch=same), (8, 3, 16, 16)),
+ "RandomHorizontalFlip3D": (lambda p, same: K.RandomHorizontalFlip3D(p=p, same_on_batch=same), (8, 3, 4, 8, 8)),
+ "RandomMixUpV2": (lambda p, same: K.RandomMixUpV2(p=p, same_on_batch=same), (8, 3, 16, 16)),
+}
+# Mix augmentations run on an empty batch (Review Focus 4).
+_EMPTY_BATCH_MIX = {
+ "RandomCutMixV2": lambda: K.RandomCutMixV2(p=1.0, use_correct_lambda=True),
+ "RandomMixUpV2": lambda: K.RandomMixUpV2(p=1.0),
+}
+# Host reads that only happen because the caller moved the parameters to CUDA: the crop window and the padding set
+# the sizes of Python slices.
+_REPLAY_DEVICE_READS = {
+ "RandomCrop": {"geometry/transform/crop2d.py:crop_by_indices", "augmentation/_2d/geometric/crop.py:apply_transform"}
+}
+
+
+def test_registry_covers_public_augmentations() -> None:
+ public = set()
+ for module in (K, KAuto, KContainer, KPresets, KAda):
+ for name in dir(module):
+ obj = getattr(module, name)
+ if name.startswith("_"):
+ continue
+ if inspect.isclass(obj) and issubclass(obj, (_BasicAugmentationBase, ImageSequential)):
+ public.add(obj.__name__)
+ registered = {case.name for case in AUG_CASES}
+ missing = sorted(public - registered - EXCLUDED.keys())
+ assert not missing, f"Register these augmentations in testing/augmentation/sync_registry.py: {missing}"
+
+
[email protected](not torch.cuda.is_available(), reason="CUDA host synchronizations need a CUDA device")
+class TestAugmentationHostSync(BaseTester):
+ @pytest.mark.parametrize("case, which", _CALLS)
+ def test_no_avoidable_host_sync(self, case, which, device, dtype) -> None:
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+ fn = make_call(case, which, device, dtype)
+ try:
+ fn()
+ except (RuntimeError, NotImplementedError, TypeError) as error:
+ if dtype not in _HALF:
+ raise
+ pytest.skip(f"{case.name} does not run in {dtype}: {error}")
+ torch.cuda.synchronize()
+ sites = sync_sites(fn)
+ assert not set(sites) - INHERENT_SITES.keys(), dict(sites)
+
+ @pytest.mark.parametrize("placement", ["cpu", "cuda"])
+ @pytest.mark.parametrize("name", sorted(_REPLAY))
+ def test_replay_params_cuda_and_cpu(self, name, placement, device, dtype) -> None:
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+ op = _REPLAY[name]()
+ x = torch.rand(4, 3, 32, 32, device=device, dtype=dtype)
+ first = op(x)
+ params = {
+ k: v.to(device) if placement == "cuda" and isinstance(v, torch.Tensor) else v for k, v in op._params.items()
+ }
+ torch.cuda.synchronize()
+ replayed = []
+ sites = sync_sites(lambda: replayed.append(op(x, params=params)))
+ assert torch.equal(replayed[0], first)
+ # Cropping reads the crop window on the host to slice; that is inherent when the caller moved it to CUDA.
+ allowed = INHERENT_SITES.keys() | (_REPLAY_DEVICE_READS.get(name, set()) if placement == "cuda" else set())
+ assert not set(sites) - allowed, dict(sites)
+
+ @pytest.mark.parametrize("name", ["RandomCutMixV2", "RandomMixUpV2"])
+ def test_empty_batch_mix(self, name, device, dtype) -> None:
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+ op = _EMPTY_BATCH_MIX[name]()
+ x = torch.rand(0, 3, 32, 32, device=device, dtype=dtype)
+ op(x)
+ torch.cuda.synchronize()
+ outputs = []
+ sites = sync_sites(lambda: outputs.append(op(x)))
+ assert outputs[0].shape == x.shape
+ assert outputs[0].device == x.device
+ assert not set(sites) - INHERENT_SITES.keys(), dict(sites)
+
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("name", sorted(_GATED))
+ def test_gate_selection_unchanged(self, name, p, same_on_batch, device, dtype) -> None:
+ if device.type != "cuda":
+ pytest.skip("CUDA host synchronizations need a CUDA device")
+ build, shape = _GATED[name]
+ op = build(p, same_on_batch)
+ x = torch.rand(*shape, device=device, dtype=dtype)
+ op(x)
+ torch.cuda.synchronize()
+ outputs = []
+ sites = sync_sites(lambda: outputs.append(op(x)))
+ assert not set(sites) - INHERENT_SITES.keys(), dict(sites)
+ params = op._params
+ # The gated rows are the always-applied result of the same parameters; the others are the input itself.
+ reference = build(1.0, same_on_batch)(x, params=params)
+ applied = torch.atleast_1d(params["batch_prob"] > 0.5).to(device)
+ if applied.shape[0] != x.shape[0]: # a batch-level gate, as the mix augmentations draw it
+ applied = applied.expand(x.shape[0])
+ expected = torch.where(applied.view(-1, *([1] * (x.dim() - 1))), reference, x)
+ assert torch.equal(outputs[0], expected)
+
+
+class TestMaskWritesWithoutHostReads(BaseTester):
+ """RandomRain and RandomSaltAndPepperNoise write their pixels without a ``nonzero`` (seeds 0 to 4)."""
+
+ @pytest.mark.parametrize("seed", range(5))
+ def test_rain_and_salt_pepper_values_unchanged(self, seed, device, dtype) -> None:
+ x = torch.rand(4, 3, 32, 32, generator=torch.Generator().manual_seed(seed)).to(device, dtype)
+
+ # Salt and pepper: the same writes as the boolean indexing they replace, salt first.
+ torch.manual_seed(seed)
+ noise = K.RandomSaltAndPepperNoise(p=1.0)
+ out = noise(x)
+ expected = x.clone()
+ expected[noise._params["mask_salt"].to(device)] = 1.0
+ expected[noise._params["mask_pepper"].to(device)] = 0.0
+ assert torch.equal(out, expected)
+
+ # Rain: every drop pixel takes 200 / 255 in all channels and every other pixel keeps the input, and the
+ # replayed parameters give the same image on the CPU and on the device.
+ torch.manual_seed(seed)
+ rain = K.RandomRain(p=1.0)
+ out = rain(x)
+ changed = (out != x).any(dim=1, keepdim=True).expand_as(out)
+ assert changed.any()
+ drop_value = torch.full((), 200 / 255, dtype=dtype)
+ assert torch.equal(out[changed].cpu(), drop_value.expand(int(changed.sum())))
+ assert torch.equal(out[~changed], x[~changed])
+ params = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in rain._params.items()}
+ assert torch.equal(rain(x.cpu(), params=params), out.cpu())
+
+
[email protected](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
+ # erasing mask is built on the device from the box parameters, so only the parameters cross.
+ device = torch.device("cuda")
+ op = K.RandomErasing(p=1.0)
+ x = torch.rand(8, 3, 64, 64, device=device)
+ op(x)
+ torch.cuda.synchronize()
+ with torch.profiler.profile(
+ activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA]
+ ) as prof:
+ op(x)
+ torch.cuda.synchronize()
+ trace = tmp_path / "trace.json"
+ prof.export_chrome_trace(str(trace))
+ events = json.loads(trace.read_text())["traceEvents"]
+ copied = sum(e.get("args", {}).get("bytes", 0) for e in events if "Memcpy HtoD" in e.get("name", ""))
+ mask_bytes = 8 * 64 * 64 * 4
+ assert copied < mask_bytes // 4, copied
+
+
+def _shape_literal_cases() -> dict:
+ from kornia.filters import get_gaussian_kernel1d
+ from kornia.geometry.transform.affwarp import _compute_tensor_center, _compute_tensor_center3d
+
+ def flip(cls):
+ return lambda x: cls(p=1.0).compute_transformation(x, {}, {})
+
+ return {
+ "tensor_center": lambda x: _compute_tensor_center(x[:, :, 0]),
+ "tensor_center3d": _compute_tensor_center3d,
+ "gaussian_kernel1d": lambda x: get_gaussian_kernel1d(x.shape[-1], torch.full((1, 1), 1.5, device=x.device)),
+ "RandomHorizontalFlip3D": flip(K.RandomHorizontalFlip3D),
+ "RandomVerticalFlip3D": flip(K.RandomVerticalFlip3D),
+ "RandomDepthicalFlip3D": flip(K.RandomDepthicalFlip3D),
+ }
+
+
[email protected]("name", sorted(_shape_literal_cases()))
+def test_dynamo_shape_derived_literals_compile_once(name, device, torch_optimizer, optimizer_backend) -> None:
+ # Literals built from sizes stay symbolic under a dynamic compile: one graph for every size, no guard on a value.
+ from torch._dynamo.testing import CompileCounter
+
+ if optimizer_backend == "jit":
+ pytest.skip("counts the graphs of torch.compile, which torch.jit.script does not build")
+ op = _shape_literal_cases()[name]
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, dynamic=True, fullgraph=True)
+ for size in (9, 11, 13):
+ x = torch.rand(2, 3, size, size + 2, size + 4, device=device)
+ assert torch.equal(compiled(x), op(x))
+ assert counter.frame_count == 1
+
+
+def test_dynamo_literals_stay_graph_constants(device, torch_optimizer, optimizer_backend) -> None:
+ # Under torch.compile a literal stays a constant of the graph, which Inductor folds into its consumer: the
+ # compiled grayscale is one kernel, as before. Filling the weights on the device would add a stack kernel per call.
+ if optimizer_backend != "inductor" or device.type != "cuda":
+ pytest.skip("counts the CUDA kernels of an Inductor graph")
+ x = torch.rand(8, 3, 64, 64, device=device)
+ compiled = torch_optimizer(K.RandomGrayscale(p=1.0))
+ compiled(x)
+ torch.cuda.synchronize()
+ with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof:
+ compiled(x)
+ torch.cuda.synchronize()
+ kernels = [e.name for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA]
+ assert len(kernels) == 1, kernels
diff --git a/tests/color/test_gray.py b/tests/color/test_gray.py
index 11bdcd256..850c709f6 100644
--- a/tests/color/test_gray.py
+++ b/tests/color/test_gray.py
@@ -129,6 +129,13 @@ class TestRgbToGrayscale(BaseTester):
assert out.device == img.device
assert out.dtype == img.dtype
+ def test_jit_script(self, device, dtype):
+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ op_jit = torch.jit.script(kornia.color.rgb_to_grayscale)
+ self.assert_close(op_jit(img), kornia.color.rgb_to_grayscale(img))
+ module_jit = torch.jit.script(kornia.color.RgbToGrayscale())
+ self.assert_close(module_jit(img), kornia.color.rgb_to_grayscale(img))
+
def test_smoke_byte(self, device):
C, H, W = 3, 4, 5
img = torch.randint(0, 255, (C, H, W), device=device, dtype=torch.uint8)
diff --git a/tests/core/test_device_transfer.py b/tests/core/test_device_transfer.py
new file mode 100644
index 000000000..a5023e03c
--- /dev/null
+++ b/tests/core/test_device_transfer.py
@@ -0,0 +1,203 @@
+# 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
+
+import pytest
+import torch
+
+import kornia.augmentation.utils.helpers as augmentation_helpers
+from kornia.core import ops as core_ops
+from kornia.core.utils import _to_device_nonblocking, _torch_inverse_cast
+
+from testing.base import BaseTester
+
+requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
+
+# About 3 ms of queued GPU work on a current GPU, so that a copy which waited for the queue would be visible.
+_SLEEP_CYCLES = 5_000_000
+
+
+def _source(shape: tuple[int, ...], device: torch.device, dtype: torch.dtype = torch.float64) -> torch.Tensor:
+ # Values that round differently in every narrower dtype, including exact ties of float16 and bfloat16. MPS has no
+ # float64, so its tests pass ``dtype=torch.float32`` (the ties are exact in float32 too).
+ values = torch.randn(shape, dtype=torch.float64) * 1000.0
+ if values.numel():
+ values.view(-1)[0] = 1.0 + 2.0**-11 # a float16 tie
+ values.view(-1)[-1] = 1.0 + 2.0**-8 # a bfloat16 tie
+ return values.to(dtype).to(device)
+
+
+class TestToDeviceNonblocking(BaseTester):
+ @pytest.mark.parametrize("direction", ["host_to_device", "device_to_host", "same_device"])
+ @pytest.mark.parametrize("shape", [(4, 5), (0, 3)])
+ def test_values_equal_blocking_copy(self, direction, shape, device, dtype) -> None:
+ cpu = torch.device("cpu")
+ src_device, dst_device = {
+ "host_to_device": (cpu, device),
+ "device_to_host": (device, cpu),
+ "same_device": (device, device),
+ }[direction]
+ src = _source(shape, src_device, torch.float32 if device.type == "mps" else torch.float64)
+ for target_dtype in (dtype, None):
+ out = _to_device_nonblocking(src, dst_device, target_dtype)
+ expected = src.to(dst_device, target_dtype) if target_dtype is not None else src.to(dst_device)
+ assert out.device.type == dst_device.type
+ assert out.dtype == expected.dtype
+ assert torch.equal(out.cpu(), expected.cpu())
+
+ @pytest.mark.parametrize("shape", [(4, 5), (0, 3)])
+ def test_integer_values_equal_blocking_copy(self, shape, device) -> None:
+ src = torch.randint(-(2**40), 2**40, shape, dtype=torch.int64)
+ out = _to_device_nonblocking(src, device, torch.int64)
+ assert torch.equal(out.cpu(), src.to(device, torch.int64).cpu())
+
+ def test_same_device_and_dtype_returns_input(self, device, dtype) -> None:
+ src = torch.rand(3, device=device, dtype=dtype)
+ assert _to_device_nonblocking(src, device, dtype) is src
+ assert _to_device_nonblocking(src, device) is src
+
+ def test_scriptable(self, device, dtype) -> None:
+ scripted = torch.jit.script(_to_device_nonblocking)
+ src = torch.rand(3, dtype=torch.float64)
+ assert torch.equal(scripted(src, device, dtype).cpu(), src.to(device, dtype).cpu())
+
+ @requires_cuda
+ def test_cpu_to_cuda_does_not_sync(self) -> None:
+ src = torch.rand(8, 3)
+ torch.cuda.synchronize()
+ try:
+ torch.cuda.set_sync_debug_mode("error")
+ for dtype in (None, torch.float32, torch.float16, torch.float64):
+ _to_device_nonblocking(src, torch.device("cuda"), dtype)
+ finally:
+ torch.cuda.set_sync_debug_mode(0)
+
+ @requires_cuda
+ def test_source_mutation_after_copy(self) -> None:
+ cuda = torch.device("cuda")
+ for dtype in (None, torch.float16):
+ for _ in range(50):
+ src = torch.rand(64, 3)
+ expected = src.to(dtype) if dtype is not None else src.clone()
+ torch.cuda._sleep(_SLEEP_CYCLES)
+ out = _to_device_nonblocking(src, cuda, dtype)
+ src.fill_(-1.0)
+ torch.cuda.synchronize()
+ assert torch.equal(out.cpu(), expected)
+
+ @requires_cuda
+ def test_pinned_source_mutation_after_copy(self) -> None:
+ # A pinned source is copied asynchronously by a non-blocking copy, so it must be copied blocking: a caller may
+ # refill a pinned buffer straight after the call.
+ cuda = torch.device("cuda")
+ for _ in range(20):
+ src = torch.rand(64, 3).pin_memory()
+ expected = src.clone()
+ torch.cuda._sleep(_SLEEP_CYCLES)
+ out = _to_device_nonblocking(src, cuda)
+ src.fill_(-1.0)
+ torch.cuda.synchronize()
+ assert torch.equal(out.cpu(), expected)
+
+ @requires_cuda
+ @pytest.mark.parametrize("dst_dtype", [torch.float16, torch.bfloat16, torch.float32])
+ def test_cast_bits_equal_blocking_copy_including_nan_payloads(self, dst_dtype) -> None:
+ # Signalling and quiet NaNs with payloads, infinities, subnormals and ordinary values in float64 and float32.
+ bits64 = torch.tensor(
+ [0x7FF0000000000001, 0x7FF8000000001234, -0x7FFFF00000000, 0x7FF0000000000000, 1, 0x3FF0000000000001],
+ dtype=torch.int64,
+ )
+ bits32 = torch.tensor([0x7F800001, 0x7FC01234, -0x3F00001, 0x7F800000, 1, 0x3F800001], dtype=torch.int32)
+ for src in (bits64.view(torch.float64), bits32.view(torch.float32)):
+ if src.dtype == dst_dtype:
+ continue
+ out = _to_device_nonblocking(src, torch.device("cuda"), dst_dtype).cpu()
+ expected = src.to("cuda", dst_dtype).cpu()
+ assert torch.equal(
+ out.view(torch.int16 if dst_dtype != torch.float32 else torch.int32),
+ expected.view(torch.int16 if dst_dtype != torch.float32 else torch.int32),
+ )
+
+ @requires_cuda
+ def test_cuda_to_cpu_is_blocking(self) -> None:
+ x = torch.rand(256, 256)
+ x_cuda = x.cuda()
+ torch.cuda.synchronize()
+ torch.cuda._sleep(_SLEEP_CYCLES)
+ y = x_cuda * 2.0 # queued behind the sleep
+ out = _to_device_nonblocking(y, torch.device("cpu"))
+ # No synchronize: a non-blocking device-to-host copy could be read before it lands.
+ assert torch.equal(out, x * 2.0)
+ # A non-blocking device-to-host copy does not synchronize, and the host could read it too early.
+ try:
+ torch.cuda.set_sync_debug_mode("error")
+ with pytest.raises(RuntimeError, match="synchronizing"):
+ _to_device_nonblocking(y, torch.device("cpu"))
+ finally:
+ torch.cuda.set_sync_debug_mode(0)
+
+
+class TestInverseWithoutErrorCheck(BaseTester):
+ @pytest.mark.parametrize("n", [3, 4])
+ def test_inverse_without_error_check_is_identical(self, n, device, dtype) -> None:
+ # Well conditioned: the identity plus a small random perturbation.
+ a = torch.eye(n, device=device, dtype=dtype) + 0.1 * torch.randn(8, n, n, device=device, dtype=dtype)
+ expected = _torch_inverse_cast(a)
+ if device.type == "cuda":
+ torch.cuda.synchronize()
+ try:
+ torch.cuda.set_sync_debug_mode("error")
+ actual = _torch_inverse_cast(a, check_errors=False)
+ finally:
+ torch.cuda.set_sync_debug_mode(0)
+ else:
+ actual = _torch_inverse_cast(a, check_errors=False)
+ assert torch.equal(actual, expected)
+
+ def test_singular_still_raises_with_error_check(self, device, dtype) -> None:
+ with pytest.raises(RuntimeError):
+ _torch_inverse_cast(torch.zeros(1, 3, 3, device=device, dtype=dtype))
+
+
+class TestConstantTensorUnderAutocast(BaseTester):
+ @pytest.mark.parametrize("autocast_dtype", [torch.float16, torch.bfloat16])
+ def test_dtype_and_values_ignore_autocast(self, autocast_dtype, device, dtype) -> None:
+ # A literal keeps the requested dtype in an autocast region of another precision, as torch.tensor does.
+ data = [[0.299, 0.0, -1.0], [0.0, 0.587, 1.0 / 3.0]]
+ expected = torch.tensor(data, device=device, dtype=dtype)
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = core_ops._constant_tensor(data, device=device, dtype=dtype)
+ assert actual.dtype == dtype
+ assert torch.equal(actual, expected)
+
+
+def test_constant_tensor_import_paths() -> None:
+ assert augmentation_helpers._constant_tensor is core_ops._constant_tensor
+ assert augmentation_helpers._flatten_constant is core_ops._flatten_constant
+
+
+class TestDeviceLiteral(BaseTester):
+ def test_float16_out_of_range_matches_torch_tensor(self, device) -> None:
+ # torch.tensor rounds a finite literal beyond the float16 range to 65504 or to inf; torch.full raises on CUDA.
+ data = [[65505.0, 70000.0, -1.0e6], [1.0, 0.1, float("inf")]]
+ expected = torch.tensor(data, device=device, dtype=torch.float16)
+ assert torch.equal(core_ops._device_literal(data, device=device, dtype=torch.float16), expected)
+ assert torch.equal(
+ core_ops._device_literal(65505.0, device=device, dtype=torch.float16),
+ torch.tensor(65505.0, device=device, dtype=torch.float16),
+ )
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index d0b2e0829..43a0ceb1c 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -1313,3 +1313,51 @@ class TestDiffJPEG(BaseTester):
assert type(img_jpeg) is torch.Tensor
kornia.enhance.jpeg._DCT8_CACHE.clear()
self.assert_close(img_jpeg, module(img, jpeg_quality))
+
+
+class TestDefaultQuantizationTables(BaseTester):
+ def test_tables_are_built_once_per_device_and_dtype(self, device, dtype):
+ from kornia.enhance.jpeg import _default_quantization_tables, _get_default_qt_c, _get_default_qt_y
+
+ first = _default_quantization_tables(device, dtype)
+ second = _default_quantization_tables(device, dtype)
+ assert first[0] is second[0]
+ assert first[1] is second[1]
+ assert torch.equal(first[0], _get_default_qt_y(device, dtype))
+ assert torch.equal(first[1], _get_default_qt_c(device, dtype))
+
+ def test_tables_cached_in_inference_mode_still_take_gradients(self, device):
+ from kornia.enhance.jpeg import _DEFAULT_QT_CACHE
+
+ _DEFAULT_QT_CACHE.clear()
+ img = torch.rand(1, 3, 16, 16, device=device, dtype=torch.float32)
+ quality = torch.tensor([50.0], device=device)
+ with torch.inference_mode():
+ kornia.enhance.jpeg_codec_differentiable(img, quality)
+ img.requires_grad_(True)
+ kornia.enhance.jpeg_codec_differentiable(img, quality).sum().backward()
+ assert img.grad is not None
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA streams")
+ def test_cached_tables_are_complete_on_another_stream(self):
+ # The caches are shared by every stream. A call on a second stream must not read tables whose fill kernels
+ # are still queued behind other work on the stream that built them.
+ from kornia.enhance import jpeg
+
+ cuda = torch.device("cuda")
+ img = torch.rand(4, 3, 64, 64, device=cuda)
+ quality = torch.tensor([50.0, 60.0, 70.0, 80.0])
+ expected = jpeg.jpeg_codec_differentiable(img, quality)
+ first, second = torch.cuda.Stream(), torch.cuda.Stream()
+ for _ in range(5):
+ jpeg._DEFAULT_QT_CACHE.clear()
+ jpeg._DCT8_CACHE.clear()
+ jpeg._get_dct8_basis_scale(img.dtype, img.device)
+ torch.cuda.synchronize()
+ with torch.cuda.stream(first):
+ torch.cuda._sleep(50_000_000)
+ jpeg.jpeg_codec_differentiable(img, quality)
+ with torch.cuda.stream(second):
+ out = jpeg.jpeg_codec_differentiable(img, quality)
+ torch.cuda.synchronize()
+ assert torch.equal(out, expected)