π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix CUDA constant transfers across augmentation generators (#4523)
Dmytro Mishkin2cf60935b40b
diff --git a/changelog.d/4523.fixed.md b/changelog.d/4523.fixed.mdnew file mode 100644index 000000000..57c19d1b3--- /dev/null+++ b/changelog.d/4523.fixed.md@@ -0,0 +1,3 @@+Extend the CUDA `torch.compile` constant-transfer workaround to shear, thin-plate spline, erasing, crop, resize, 3D affine/perspective, and illumination/mix parameter generators. Eager execution, `torch.compile`, and `make_fx` build these constants with the same scalar factories, without a host-device copy. Crop operations retain their existing graph breaks.++Fix `RandomShear` and `RandomAffine` sampler migration so scalar and tuple shear ranges honor the requested device and dtype; moving `RandomAffine` with a scalar or two-element `shear` to CUDA used to raise a device-mismatch error. Fix mixed-device sign generation in both linear-illumination generators after moving their samplers. `CenterCrop3D` parameters for an empty batch are now `long` tensors on the requested device, matching non-empty batches, instead of CPU `float32` tensors.diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex c0a7e80f2..13c36f5c5 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.constants import Resamplefrom kornia.core.utils import is_exportingfrom kornia.geometry.boxes import Boxes@@ -349,7 +350,7 @@ class RandomCrop(GeometricAugmentationBase2D):batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding))- padding_size = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)+ padding_size = _constant_tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)_params = super().forward_parameters(batch_shape_new)_params.update({"padding_size": padding_size})return _paramsdiff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.pyindex 9d531b774..dd9fb7d6b 100644--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation._2d.base import AugmentationBase2D+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.constants import SamplePaddingfrom kornia.geometry.transform import get_tps_transform, warp_image_tps@@ -79,7 +80,7 @@ class RandomThinPlateSpline(AugmentationBase2D):dtype = self.dtype# 5 TPS control points in normalized coordinates- src = torch.tensor(+ src = _constant_tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]],device=device,dtype=dtype,diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex 4b9137bb6..cbd1c9461 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -102,7 +102,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:params = super().generate_parameters(batch_shape)- params["idx"] = torch.tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))+ params["idx"] = torch.zeros(1, dtype=torch.long) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))return paramsdef apply_transform(diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex 96f052b5d..59bd870e9 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -226,7 +226,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):in_tensor: torch.Tensor = input[in_tensor_idx]in_tensor = self.transform_tensor(in_tensor)self._params = self.forward_parameters(in_tensor.shape)- self._params.update({"dtype": torch.tensor(DType.get(in_tensor.dtype).value)})+ self._params.update({"dtype": torch.full((), DType.get(in_tensor.dtype).value, dtype=torch.long)})else:self._params = paramsdiff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 5481d6c28..498e6b58d 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -26,6 +26,7 @@ from kornia.augmentation.utils import (_transform_output_shape,override_parameters,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -274,7 +275,7 @@ class _BasicAugmentationBase(nn.Module):_params["batch_prob"] = batch_prob# Added another input_size parameter for geometric transformations# This might be needed for correctly inversing.- input_size = torch.tensor(batch_shape, dtype=torch.long)+ input_size = _constant_tensor(batch_shape, dtype=torch.long)_params.update({"forward_input_shape": input_size})return _params@@ -306,7 +307,7 @@ class _BasicAugmentationBase(nn.Module):params = self.forward_parameters(batch_shape)if "batch_prob" not in params:- params["batch_prob"] = torch.tensor([True] * batch_shape[0])+ params["batch_prob"] = torch.ones(batch_shape[0], dtype=torch.bool)params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.pyindex 56e872278..4c0c107ac 100644--- a/kornia/augmentation/random_generator/_2d/affine.py+++ b/kornia/augmentation/random_generator/_2d/affine.py@@ -26,7 +26,9 @@ from kornia.augmentation.utils import (_common_param_check,_joint_range_check,_range_bound,+ _shear_bound,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype__all__ = ["AffineGenerator"]@@ -111,20 +113,7 @@ class AffineGenerator(RandomGeneratorBase):raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")_shear: Optional[torch.Tensor] = Noneif self.shear is not None:- shear = torch.as_tensor(self.shear, device=device, dtype=dtype)- if shear.shape == torch.Size([2, 2]):- _shear = shear- else:- _shear = torch.stack(- [- _range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),- (- torch.tensor([0, 0], device=device, dtype=dtype)- if shear.dim() == 0 or len(shear) == 2- else _range_bound(shear[2:], "shear-y", 0, (-360, 360))- ),- ]- )+ _shear = _shear_bound(self.shear, device, dtype)translate_x_sampler: Optional[UniformDistribution] = Nonetranslate_y_sampler: Optional[UniformDistribution] = None@@ -191,12 +180,7 @@ class AffineGenerator(RandomGeneratorBase):else:translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)- # Stack scalar factories without indexed fills: those also lift CPU constants- # that Inductor can reuse in CUDA kernels without copying the parameters.- # See https://github.com/pytorch/pytorch/issues/196969.- center = torch.stack(- [torch.full((), width, device=_device, dtype=_dtype), torch.full((), height, device=_device, dtype=_dtype)]- ).view(1, 2)+ center = _constant_tensor([width, height], device=_device, dtype=_dtype).view(1, 2)center = center / 2.0 - 0.5center = center.expand(batch_size, -1)diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.pyindex b439fac5b..c2b644fd6 100644--- a/kornia/augmentation/random_generator/_2d/crop.py+++ b/kornia/augmentation/random_generator/_2d/crop.py@@ -27,6 +27,7 @@ from kornia.augmentation.utils import (_common_param_check,_joint_range_check,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator@@ -82,7 +83,7 @@ class CropGenerator(RandomGeneratorBase):input_size = (batch_shape[-2], batch_shape[-1])if not isinstance(self.size, torch.Tensor):- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)+ size = _constant_tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)if size.shape != torch.Size([batch_size, 2]):raise AssertionError(f"`size` must be a (height, width) pair of integers or a (B, 2) tensor. Got {self.size!r}."@@ -122,14 +123,14 @@ class CropGenerator(RandomGeneratorBase):crop_src = bbox_generator(x_start.view(-1).to(device=_device, dtype=_dtype),y_start.view(-1).to(device=_device, dtype=_dtype),- torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),+ torch.where(size[:, 1] == 0, torch.full((), input_size[1], device=_device, dtype=_dtype), size[:, 1]),+ torch.where(size[:, 0] == 0, torch.full((), input_size[0], device=_device, dtype=_dtype), size[:, 0]),)if self.resize_to is None:crop_dst = bbox_generator(- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ torch.zeros(batch_size, device=_device, dtype=_dtype),+ torch.zeros(batch_size, device=_device, dtype=_dtype),size[:, 1],size[:, 0],)@@ -143,7 +144,7 @@ class CropGenerator(RandomGeneratorBase):and self.resize_to[1] > 0):raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")- crop_dst = torch.tensor(+ crop_dst = _constant_tensor([[[0, 0],@@ -155,9 +156,9 @@ class CropGenerator(RandomGeneratorBase):device=_device,dtype=_dtype,).repeat(batch_size, 1, 1)- _output_size = torch.tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)+ _output_size = _constant_tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)+ _input_size = _constant_tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)return {"src": crop_src, "dst": crop_dst, "input_size": _input_size, "output_size": _output_size}@@ -251,7 +252,11 @@ class ResizedCropGenerator(CropGenerator):rand_tensor = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)- scale_tensor = torch.as_tensor(self.scale, device=_device, dtype=_dtype)+ scale_tensor = (+ self.scale.to(device=_device, dtype=_dtype)+ if isinstance(self.scale, torch.Tensor)+ else _constant_tensor(self.scale, device=_device, dtype=_dtype)+ )area = (rand_tensor * (scale_tensor[1] - scale_tensor[0]) + scale_tensor[0]) * size[0] * size[1]log_ratio = _adapted_rsampling((batch_size, 10), self.log_ratio_sampler, same_on_batch).to(device=_device, dtype=_dtype@@ -279,14 +284,14 @@ class ResizedCropGenerator(CropGenerator):in_ratio = float(size[0]) / float(size[1])_min = float(self.ratio.min()) if isinstance(self.ratio, torch.Tensor) else min(self.ratio)if in_ratio < _min:- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)+ h_ct = torch.full((), size[0], device=_device, dtype=_dtype)w_ct = torch.round(h_ct / _min)elif in_ratio > _min:- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)+ w_ct = torch.full((), size[1], device=_device, dtype=_dtype)h_ct = torch.round(w_ct * _min)else: # whole image- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)+ h_ct = torch.full((), size[0], device=_device, dtype=_dtype)+ w_ct = torch.full((), size[1], device=_device, dtype=_dtype)h_ct = h_ct.floor()w_ct = w_ct.floor()@@ -355,17 +360,17 @@ def center_crop_generator(# [y, x] origin# top-left, top-right, bottom-right, bottom-left- points_src: torch.Tensor = torch.tensor(+ points_src: torch.Tensor = _constant_tensor([[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]], device=device, dtype=torch.long).expand(batch_size, -1, -1)# [y, x] destination# top-left, top-right, bottom-right, bottom-left- points_dst: torch.Tensor = torch.tensor(+ points_dst: torch.Tensor = _constant_tensor([[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=device, dtype=torch.long).expand(batch_size, -1, -1)- _input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)- _output_size = torch.tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)+ _input_size = _constant_tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)+ _output_size = _constant_tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)return {"src": points_src, "dst": points_dst, "input_size": _input_size, "output_size": _output_size}diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex c17c17345..1a0a7e82f 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -28,6 +28,7 @@ from kornia.augmentation.utils import (_common_param_check,_joint_range_check,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator@@ -170,5 +171,5 @@ class CutmixGenerator(RandomGeneratorBase):return {"mix_pairs": mix_pairs.to(device=_device, dtype=torch.long),"crop_src": crop_src.floor().to(device=_device, dtype=_dtype),- "image_shape": torch.as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),+ "image_shape": _constant_tensor(batch_shape[-2:], device=_device, dtype=_dtype),}diff --git a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py b/kornia/augmentation/random_generator/_2d/gaussian_illumination.pyindex 610382f67..efe0fe920 100644--- a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py+++ b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py@@ -115,11 +115,9 @@ class GaussianIlluminationGenerator(RandomGeneratorBase):center_y = torch.round(height * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch))- sign = torch.where(- _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0,- torch.tensor(1.0, device=_device, dtype=_dtype),- torch.tensor(-1.0, device=_device, dtype=_dtype),- )+ sign = (_adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0).to(+ device=_device, dtype=_dtype+ ) * 2 - 1# Generate random gaussian for create a 2D gaussian image.gauss_x = gaussian(width, sigma_x, mean=center_x, device=_device, dtype=_dtype).unsqueeze(1)diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.pyindex 7d6b0240d..97fb94889 100644--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py@@ -80,11 +80,8 @@ class LinearIlluminationGenerator(RandomGeneratorBase):gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(device=_device, dtype=_dtype)- sign = torch.where(- _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0,- torch.tensor(1, device=_device, dtype=_dtype),- torch.tensor(-1, device=_device, dtype=_dtype),- )+ sign_positive = _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0+ sign = sign_positive.to(device=_device, dtype=_dtype) * 2 - 1# Directions (0=lower,1=upper,2=left,3=right), shape [B,1,1,1]directions = _adapted_rsampling((batch_size, 1, 1, 1), self.directions_sampler, same_on_batch).to(@@ -170,11 +167,8 @@ class LinearCornerIlluminationGenerator(RandomGeneratorBase):gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(device=_device, dtype=_dtype)- sign = torch.where(- _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0,- torch.tensor(1, device=_device, dtype=_dtype),- torch.tensor(-1, device=_device, dtype=_dtype),- )+ sign_positive = _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0+ sign = sign_positive.to(device=_device, dtype=_dtype) * 2 - 1directions = _adapted_rsampling((batch_size, 1, 1, 1), self.directions_sampler, same_on_batch).to(device=_device,diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.pyindex ac203cf3d..bc3df18ec 100644--- a/kornia/augmentation/random_generator/_2d/mosaic.py+++ b/kornia/augmentation/random_generator/_2d/mosaic.py@@ -22,6 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator@@ -104,7 +105,7 @@ class MosaicGenerator(RandomGeneratorBase):start_corner_x.clone().fill_(input_sizes[1]),start_corner_y.clone().fill_(input_sizes[0]),)- crop_dst = torch.tensor(+ crop_dst = _constant_tensor([[[0, 0], [input_sizes[1] - 1, 0], [input_sizes[1] - 1, input_sizes[0] - 1], [0, input_sizes[0] - 1]]],device=_device,dtype=_dtype,@@ -116,7 +117,7 @@ class MosaicGenerator(RandomGeneratorBase):if batch_size == 0:batch_shapes = torch.zeros([0, 3], device=_device, dtype=torch.long)else:- batch_shapes = torch.stack([torch.as_tensor(batch_shape[1:], device=_device) for _ in range(batch_size)])+ batch_shapes = _constant_tensor(batch_shape[1:], device=_device, dtype=torch.long).repeat(batch_size, 1)return {"permutation": mosiac_ids.to(device=_device, dtype=torch.long),"src": crop_src,diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex 1a78f6670..11fc1f973 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -22,6 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _check_positive_int_or_traced, _common_param_check+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype__all__ = ["PerspectiveGenerator"]@@ -80,15 +81,13 @@ class PerspectiveGenerator(RandomGeneratorBase):_check_positive_int_or_traced(height, "height")_check_positive_int_or_traced(width, "width")- # Stack scalar factories without indexed fills: those also lift CPU constants- # that Inductor can reuse in CUDA kernels without copying the parameters.- # See https://github.com/pytorch/pytorch/issues/196969.- zero = torch.zeros((), device=_device, dtype=_dtype)- x = torch.full((), width - 1, device=_device, dtype=_dtype)- y = torch.full((), height - 1, device=_device, dtype=_dtype)- # TL, TR, BR, BL. Subtract before casting: bbox_generator subtracts in the- # tensor dtype, which changes large half-precision image coordinates.- start_points = torch.stack([zero, zero, x, zero, x, y, zero, y]).view(1, 4, 2)+ # Subtract before casting: bbox_generator subtracts in the tensor dtype,+ # which changes large half-precision image coordinates.+ start_points = _constant_tensor(+ [[[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],+ device=_device,+ dtype=_dtype,+ )start_points = start_points.expand(batch_size, -1, -1)# generate random offset not larger than half of the image@@ -102,9 +101,7 @@ class PerspectiveGenerator(RandomGeneratorBase):device=_device, dtype=_dtype)if self.sampling_method == "basic":- one = torch.ones((), device=_device, dtype=_dtype)- neg_one = -one- pts_norm = torch.stack([one, one, neg_one, one, neg_one, neg_one, one, neg_one]).view(1, 4, 2)+ pts_norm = _constant_tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)offset = factor * rand_val * pts_normelif self.sampling_method == "area_preserving":offset = 2 * factor * (rand_val - 0.5)diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.pyindex c089e5e6e..5891cdf6c 100644--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py@@ -127,19 +127,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):aspect_ratios = aspect_ratios.to(device=_device, dtype=_dtype)# based on target areas and aspect ratios, rectangle params are computed- heights = torch.min(- torch.max(- torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)- ),- torch.tensor(height, device=_device, dtype=_dtype),- )-- widths = torch.min(- torch.max(- torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)- ),- torch.tensor(width, device=_device, dtype=_dtype),- )+ heights = torch.round((target_areas * aspect_ratios) ** (1 / 2)).clamp(1.0, height)+ widths = torch.round((target_areas / aspect_ratios) ** (1 / 2)).clamp(1.0, width)xs_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(device=_device, dtype=_dtype@@ -156,5 +145,5 @@ class RectangleEraseGenerator(RandomGeneratorBase):"heights": heights.floor(),"xs": xs.floor(),"ys": ys.floor(),- "values": torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),+ "values": torch.full((batch_size,), self.value, device=_device, dtype=_dtype),}diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.pyindex 04a9d93e1..9fed90fdd 100644--- a/kornia/augmentation/random_generator/_2d/resize.py+++ b/kornia/augmentation/random_generator/_2d/resize.py@@ -21,6 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _common_param_check+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.geometry.bbox import bbox_generatorfrom kornia.geometry.transform.affwarp import _side_to_image_size@@ -76,10 +77,10 @@ class ResizeGenerator(RandomGeneratorBase):input_size = h, w = (batch_shape[-2], batch_shape[-1])src = bbox_generator(- torch.tensor(0, device=_device, dtype=_dtype),- torch.tensor(0, device=_device, dtype=_dtype),- torch.tensor(input_size[1], device=_device, dtype=_dtype),- torch.tensor(input_size[0], device=_device, dtype=_dtype),+ torch.zeros((), device=_device, dtype=_dtype),+ torch.zeros((), device=_device, dtype=_dtype),+ torch.full((), input_size[1], device=_device, dtype=_dtype),+ torch.full((), input_size[0], device=_device, dtype=_dtype),).repeat(batch_size, 1, 1)if isinstance(self.output_size, int):@@ -98,13 +99,13 @@ class ResizeGenerator(RandomGeneratorBase):raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {output_size}.")dst = bbox_generator(- torch.tensor(0, device=_device, dtype=_dtype),- torch.tensor(0, device=_device, dtype=_dtype),- torch.tensor(output_size[1], device=_device, dtype=_dtype),- torch.tensor(output_size[0], device=_device, dtype=_dtype),+ torch.zeros((), device=_device, dtype=_dtype),+ torch.zeros((), device=_device, dtype=_dtype),+ torch.full((), output_size[1], device=_device, dtype=_dtype),+ torch.full((), output_size[0], device=_device, dtype=_dtype),).repeat(batch_size, 1, 1)- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)- _output_size = torch.tensor(output_size, device=_device, dtype=torch.long).expand(batch_size, -1)+ _input_size = _constant_tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)+ _output_size = _constant_tensor(output_size, device=_device, dtype=torch.long).expand(batch_size, -1)return {"src": src, "dst": dst, "input_size": _input_size, "output_size": _output_size}diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.pyindex 8a1fe5f9c..77c8d084d 100644--- a/kornia/augmentation/random_generator/_2d/shear.py+++ b/kornia/augmentation/random_generator/_2d/shear.py@@ -25,8 +25,9 @@ from kornia.augmentation.utils import (_check_positive_int_or_traced,_common_param_check,_joint_range_check,- _range_bound,+ _shear_bound,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype__all__ = ["ShearGenerator"]@@ -68,20 +69,7 @@ class ShearGenerator(RandomGeneratorBase):return reprdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:- shear = torch.as_tensor(self.shear, device=device, dtype=dtype)- if shear.shape == torch.Size([2, 2]):- _shear = shear- else:- _shear = torch.stack(- [- _range_bound(shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360)),- (- torch.tensor([0, 0], device=device, dtype=dtype)- if shear.dim() == 0 or len(shear) == 2- else _range_bound(shear[2:], "shear-y", 0, (-360, 360))- ),- ]- )+ _shear = _shear_bound(self.shear, device, dtype)_joint_range_check(_shear[0], "shear")_joint_range_check(_shear[1], "shear")@@ -104,7 +92,7 @@ class ShearGenerator(RandomGeneratorBase):_check_positive_int_or_traced(width, "width")_check_positive_int_or_traced(height, "height")- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5+ center: torch.Tensor = _constant_tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5center = center.expand(batch_size, -1)sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.pyindex bd1aaca69..9b2d4ea59 100644--- a/kornia/augmentation/random_generator/_3d/affine.py+++ b/kornia/augmentation/random_generator/_3d/affine.py@@ -26,6 +26,7 @@ from kornia.augmentation.utils import (_singular_range_check,_tuple_range_reader,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype@@ -213,7 +214,9 @@ class AffineGenerator3D(RandomGeneratorBase):translations = torch.zeros((batch_size, 3), device=_device, dtype=_dtype)# center should be in x,y,z- center: torch.Tensor = torch.tensor([width, height, depth], device=_device, dtype=_dtype).view(1, 3) / 2.0 - 0.5+ center: torch.Tensor = (+ _constant_tensor([width, height, depth], device=_device, dtype=_dtype).view(1, 3) / 2.0 - 0.5+ )center = center.expand(batch_size, -1)if self.shears is not None:@@ -224,7 +227,7 @@ class AffineGenerator3D(RandomGeneratorBase):szx = _adapted_rsampling((batch_size,), self.szx_sampler, same_on_batch)szy = _adapted_rsampling((batch_size,), self.szy_sampler, same_on_batch)else:- sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)+ sxy = sxz = syx = syz = szx = szy = torch.zeros(batch_size, device=_device, dtype=_dtype)return {"translations": torch.as_tensor(translations, device=_device, dtype=_dtype),diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.pyindex 9fc37d68e..db9797fea 100644--- a/kornia/augmentation/random_generator/_3d/crop.py+++ b/kornia/augmentation/random_generator/_3d/crop.py@@ -22,6 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _check_positive_int_or_traced, _common_param_check+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype, is_exportingfrom kornia.geometry.bbox import bbox_generator3d@@ -70,7 +71,7 @@ class CropGenerator3D(RandomGeneratorBase):_device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])if not isinstance(self.size, torch.Tensor):- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)+ size = _constant_tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)else:size = self.size.to(device=_device, dtype=_dtype)if size.shape != torch.Size([batch_size, 3]):@@ -118,9 +119,9 @@ class CropGenerator3D(RandomGeneratorBase):if self.resize_to is None:crop_dst = bbox_generator3d(- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),+ torch.zeros(batch_size, device=_device, dtype=_dtype),+ torch.zeros(batch_size, device=_device, dtype=_dtype),+ torch.zeros(batch_size, device=_device, dtype=_dtype),size[:, 2] - 1,size[:, 1] - 1,size[:, 0] - 1,@@ -136,7 +137,7 @@ class CropGenerator3D(RandomGeneratorBase):and self.resize_to[2] > 0):raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")- crop_dst = torch.tensor(+ crop_dst = _constant_tensor([[[0, 0, 0],@@ -198,8 +199,6 @@ def center_crop_generator3d():raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")- if batch_size == 0:- return {"src": torch.zeros([0, 8, 3]), "dst": torch.zeros([0, 8, 3])}# unpack input sizesdst_d, dst_h, dst_w = sizesrc_d, src_h, src_w = (depth, height, width)@@ -224,7 +223,7 @@ def center_crop_generator3d(# top-left-back, top-right-back, bottom-right-back, bottom-left-back# Note: DeprecationWarning: an integer is required (got type float).# Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.- points_src: torch.Tensor = torch.tensor(+ points_src: torch.Tensor = _constant_tensor([[[int(start_x), int(start_y), int(start_z)],@@ -244,7 +243,7 @@ def center_crop_generator3d(# [x, y, z] destination# top-left-front, top-right-front, bottom-right-front, bottom-left-front# top-left-back, top-right-back, bottom-right-back, bottom-left-back- points_dst: torch.Tensor = torch.tensor(+ points_dst: torch.Tensor = _constant_tensor([[[0, 0, 0],diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.pyindex b5e2a75a4..5b77dc612 100644--- a/kornia/augmentation/random_generator/_3d/perspective.py+++ b/kornia/augmentation/random_generator/_3d/perspective.py@@ -22,6 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype@@ -70,14 +71,14 @@ class PerspectiveGenerator3D(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([self.distortion_scale])- start_points: torch.Tensor = torch.tensor(+ start_points: torch.Tensor = _constant_tensor([[- [0.0, 0, 0],+ [0, 0, 0],[width - 1, 0, 0],[width - 1, height - 1, 0],[0, height - 1, 0],- [0.0, 0, depth - 1],+ [0, 0, depth - 1],[width - 1, 0, depth - 1],[width - 1, height - 1, depth - 1],[0, height - 1, depth - 1],@@ -98,7 +99,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):device=_device, dtype=_dtype)- pts_norm = torch.tensor(+ pts_norm = _constant_tensor([[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],device=_device,dtype=_dtype,diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.pyindex 23bda9f16..3dd8172d4 100644--- a/kornia/augmentation/utils/__init__.py+++ b/kornia/augmentation/utils/__init__.py@@ -46,6 +46,7 @@ from kornia.augmentation.utils.param_validation import (_common_param_check,_joint_range_check,_range_bound,+ _shear_bound,_singular_range_check,_tuple_range_reader,)@@ -62,6 +63,7 @@ __all__ = ["_joint_range_check","_range_bound","_shape_validation",+ "_shear_bound","_singular_range_check","_transform_input","_transform_input3d",diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 760da8407..9086daea2 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathfrom functools import wrapsfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union@@ -25,6 +26,62 @@ from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.keypoints import Keypoints+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 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/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex 1c09a3ce2..4dc6d01d3 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -103,6 +103,29 @@ def _range_bound(return factor_bound+def _shear_bound(+ shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],+ device: torch.device,+ dtype: torch.dtype,+) -> torch.Tensor:+ r"""Return the x- and y-axis shear ranges as a (2, 2) tensor on ``device`` in ``dtype``.++ A float or an (a, b) pair only shears along the x axis, (a, b, c, d) also gives a y-axis+ range, and a (2, 2) tensor already holds both ranges.+ """+ shear = torch.as_tensor(shear, device=device, dtype=dtype)+ if shear.shape == torch.Size([2, 2]):+ return shear+ shear_x = _range_bound(+ shear if shear.dim() == 0 else shear[:2], "shear-x", 0, (-360, 360), device=device, dtype=dtype+ )+ if shear.dim() == 0 or len(shear) == 2:+ shear_y = torch.zeros(2, device=device, dtype=dtype)+ else:+ shear_y = _range_bound(shear[2:], "shear-y", 0, (-360, 360), device=device, dtype=dtype)+ return torch.stack([shear_x, shear_y])++def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:"""Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]."""if bounds is None:diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex f7a4c98bb..44d1f2a16 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -650,9 +650,7 @@ def bbox_generator3d()# front- bbox = torch.tensor(- [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], device=x_start.device, dtype=x_start.dtype- ).repeat(x_start.numel(), 1, 1)+ bbox = torch.zeros((x_start.numel(), 4, 3), device=x_start.device, dtype=x_start.dtype)bbox[:, :, 0] += x_start.view(-1, 1)bbox[:, :, 1] += y_start.view(-1, 1)diff --git a/tests/augmentation/test_parameter_constants.py b/tests/augmentation/test_parameter_constants.pynew file mode 100644index 000000000..29cdc644a--- /dev/null+++ b/tests/augmentation/test_parameter_constants.py@@ -0,0 +1,286 @@+# 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 functools import partial++import numpy as np+import pytest+import torch+from torch.fx.experimental.proxy_tensor import make_fx++import kornia.augmentation as K+from kornia.augmentation import random_generator as rg+from kornia.augmentation.utils.helpers import _constant_tensor++from testing.base import BaseTester++# Numeric constructor inputs deliberately keep the generated parameters on CPU.+# Include both branches which construct destination corners in crop generators.+GENERATORS = [+ pytest.param(lambda: rg.AffineGenerator(30.0), (4, 3, 16, 19), id="affine"),+ pytest.param(lambda: rg.PerspectiveGenerator(0.5), (4, 3, 16, 19), id="perspective"),+ pytest.param(lambda: rg.ShearGenerator((-10.0, 10.0)), (4, 3, 16, 19), id="shear"),+ pytest.param(lambda: rg.RectangleEraseGenerator((0.1, 0.2), (0.8, 1.2), 0.5), (4, 3, 16, 19), id="erasing"),+ pytest.param(lambda: rg.CropGenerator((8, 9)), (4, 3, 16, 19), id="crop"),+ pytest.param(lambda: rg.CropGenerator((8, 9), resize_to=(6, 7)), (4, 3, 16, 19), id="crop-resize"),+ pytest.param(lambda: rg.ResizedCropGenerator((8, 9), (0.5, 1.0), (0.8, 1.2)), (4, 3, 16, 19), id="resized-crop"),+ pytest.param(lambda: partial(rg.center_crop_generator, size=(8, 9)), (4, 16, 19), id="center-crop"),+ pytest.param(lambda: rg.ResizeGenerator((8, 9)), (4, 3, 16, 19), id="resize"),+ pytest.param(lambda: rg.AffineGenerator3D(30.0), (4, 3, 12, 16, 19), id="affine3d"),+ pytest.param(lambda: rg.PerspectiveGenerator3D(0.5), (4, 3, 12, 16, 19), id="perspective3d"),+ pytest.param(lambda: rg.CropGenerator3D((6, 8, 9)), (4, 3, 12, 16, 19), id="crop3d"),+ pytest.param(lambda: rg.CropGenerator3D((6, 8, 9), resize_to=(4, 6, 7)), (4, 3, 12, 16, 19), id="crop3d-resize"),+ pytest.param(lambda: partial(rg.center_crop_generator3d, size=(6, 8, 9)), (4, 12, 16, 19), id="center-crop3d"),+ pytest.param(lambda: K.RandomThinPlateSpline(p=1.0).generate_parameters, (4, 3, 16, 19), id="tps"),+ pytest.param(lambda: rg.MosaicGenerator((8, 9)), (4, 3, 16, 19), id="mosaic"),+ pytest.param(rg.CutmixGenerator, (4, 3, 16, 19), id="cutmix"),+ pytest.param(lambda: rg.LinearIlluminationGenerator((0.1, 0.2), (0.1, 0.2)), (4, 3, 16, 19), id="linear"),+ pytest.param(+ lambda: rg.LinearCornerIlluminationGenerator((0.1, 0.2), (0.1, 0.2)), (4, 3, 16, 19), id="linear-corner"+ ),+ pytest.param(+ lambda: rg.GaussianIlluminationGenerator((0.1, 0.2), (0.1, 0.2), (0.1, 0.2), (0.1, 0.2)),+ (4, 3, 16, 19),+ id="gaussian",+ ),+]+++def generate(generator, shape):+ return generator(*shape) if isinstance(generator, partial) else generator(shape)++[email protected]("make_generator,shape", GENERATORS)+class TestParameterConstants(BaseTester):+ def test_no_lifted_constants(self, make_generator, shape):+ generator = make_generator()+ # Trace directly rather than through Dynamo: every tracer, not only torch.compile,+ # must see constants built by factories. Crop3D keeps data-dependent eager validation.+ graph = make_fx(lambda: generate(generator, shape), _error_on_data_dependent_ops=False)().graph+ lifted = [node for node in graph.nodes if node.target == torch.ops.aten.lift_fresh_copy.default]+ assert not lifted, f"Forward lifted fresh tensor constants: {lifted}"++ @pytest.mark.parametrize("moved", [False, True])+ def test_dynamo_transfer(self, make_generator, shape, moved, device, dtype, torch_optimizer):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Inductor regression covers CPU and CUDA")+ generator = make_generator()+ if moved and isinstance(generator, torch.nn.Module):+ generator.to(device=device, dtype=dtype)++ def transfer(input):+ params = generate(generator, shape)+ # Consume every parameter in an operation on the image device. Synchronizing+ # catches asynchronous invalid CPU-pointer accesses by generated CUDA kernels.+ return params, {name: value.to(input) + input for name, value in params.items()}++ input = torch.zeros((), device=device, dtype=dtype)+ compiled = torch_optimizer(transfer, fullgraph=not isinstance(generator, rg.CropGenerator3D))+ for _ in range(2):+ params, transferred = compiled(input)+ if device.type == "cuda":+ torch.cuda.synchronize()+ for name, value in transferred.items():+ assert value.device == device+ assert value.dtype == dtype+ self.assert_close(value, params[name].to(input) + input)+++AUGMENTATIONS = [+ pytest.param(lambda: K.RandomShear((-10.0, 10.0), p=1.0), (4, 3, 16, 19), id="shear"),+ pytest.param(lambda: K.RandomThinPlateSpline(p=1.0), (4, 3, 16, 19), id="tps"),+ pytest.param(lambda: K.RandomErasing(value=0.5, p=1.0), (4, 3, 16, 19), id="erasing"),+ pytest.param(lambda: K.CenterCrop((8, 9), cropping_mode="resample"), (4, 3, 16, 19), id="center-crop"),+ pytest.param(lambda: K.RandomCrop((8, 9), cropping_mode="resample"), (4, 3, 16, 19), id="crop"),+ pytest.param(lambda: K.RandomResizedCrop((8, 9), cropping_mode="resample"), (4, 3, 16, 19), id="resized-crop"),+ pytest.param(lambda: K.Resize((8, 9)), (4, 3, 16, 19), id="resize"),+ pytest.param(lambda: K.RandomAffine3D(30.0, p=1.0), (2, 3, 8, 10, 12), id="affine3d"),+ pytest.param(lambda: K.RandomPerspective3D(0.2, p=1.0), (2, 3, 8, 10, 12), id="perspective3d"),+ pytest.param(lambda: K.RandomCrop3D((4, 6, 7)), (2, 3, 8, 10, 12), id="crop3d"),+ pytest.param(lambda: K.CenterCrop3D((4, 6, 7)), (2, 3, 8, 10, 12), id="center-crop3d"),+]+++class TestAugmentationConstantTransfer(BaseTester):+ @pytest.mark.parametrize("make_aug,shape", AUGMENTATIONS)+ @pytest.mark.parametrize("moved", [False, True])+ def test_dynamo_replay(self, make_aug, shape, moved, device, dtype, torch_optimizer):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Inductor regression covers CPU and CUDA")+ aug = make_aug()+ if moved:+ aug.to(device=device, dtype=dtype)+ input = torch.rand(shape, device=device, dtype=dtype)++ def apply(input):+ params = aug.forward_parameters(input.shape)+ return aug(input, params=params), params++ # RandomCrop reads replayable padding from tensors; Crop3D validates crop sizes.+ # These pre-existing graph breaks are separate from constant transfer safety.+ compiled = torch_optimizer(apply, fullgraph=not isinstance(aug, (K.RandomCrop, K.RandomCrop3D)))+ for _ in range(2):+ actual, params = compiled(input)+ if device.type == "cuda":+ torch.cuda.synchronize()+ self.assert_close(actual, aug(input, params=params))+++CONSTANT_DATA = [+ [],+ [[], []],+ [True, False],+ [257, 2049],+ [[0, 2048], [256, -1]],+ [[[1.5, -2.5]]],+ [0.0, -0.0, 1.0, 1],+ [[0.0, -0.0], [-0.0, 0.0]],+]+++class TestConstantTensor(BaseTester):+ @pytest.mark.parametrize("data", CONSTANT_DATA)+ def test_values(self, data, device, dtype):+ expected = torch.tensor(data, device=device, dtype=dtype)+ actual = _constant_tensor(data, device=device, dtype=dtype)+ assert actual.shape == expected.shape+ assert actual.device == device+ assert actual.dtype == dtype+ self.assert_close(actual, expected, rtol=0, atol=0)+ assert torch.equal(actual.signbit(), expected.signbit())++ @pytest.mark.parametrize("data", CONSTANT_DATA)+ def test_dynamo_values(self, data, device, dtype, torch_optimizer):+ compiled = torch_optimizer(lambda: _constant_tensor(data, device=device, dtype=dtype), fullgraph=True)+ self.assert_close(compiled(), torch.tensor(data, device=device, dtype=dtype), rtol=0, atol=0)++ def test_integer_coordinates(self, device):+ data = [[4.5, 5.5], [12.5, 13.5]]+ expected = torch.tensor([[4, 5], [12, 13]], device=device, dtype=torch.long)+ self.assert_close(_constant_tensor(data, device=device, dtype=torch.long), expected)++ def test_dynamo_integer_coordinates(self, device, torch_optimizer):+ data = [[4.5, 5.5], [12.5, 13.5]]+ expected = torch.tensor([[4, 5], [12, 13]], device=device, dtype=torch.long)+ compiled = torch_optimizer(lambda: _constant_tensor(data, device=device, dtype=torch.long), fullgraph=True)+ self.assert_close(compiled(), expected)++ def test_numpy(self, device, dtype):+ data = np.array([[0.5, 1.0], [2.0, -3.0]])+ expected = torch.as_tensor(data, device=device, dtype=dtype)+ self.assert_close(_constant_tensor(data, device=device, dtype=dtype), expected, rtol=0, atol=0)++ def test_repeated_values_fill_once(self, device, dtype):+ # Box corners repeat their coordinates: one fill per distinct value, then one stack.+ data = [[[0, 0], [18, 0], [18, 15], [0, 15]]]+ graph = make_fx(lambda: _constant_tensor(data, device=device, dtype=dtype))().graph+ targets = [node.target for node in graph.nodes if node.op == "call_function"]+ assert targets.count(torch.ops.aten.full.default) == 3+ assert targets.count(torch.ops.aten.stack.default) == 1+ assert torch.ops.aten.lift_fresh_copy.default not in targets++ def test_signed_zeros_fill_once(self, device, dtype):+ # The fill key keeps the sign, so repeated zeros merge without turning -0.0 into 0.0.+ data = [[0.0, -0.0], [-0.0, 0.0], [0.0, 1.0]]+ graph = make_fx(lambda: _constant_tensor(data, device=device, dtype=dtype))().graph+ targets = [node.target for node in graph.nodes if node.op == "call_function"]+ assert targets.count(torch.ops.aten.full.default) == 3++ def test_dynamo_dynamic_size(self, device, dtype, torch_optimizer):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Inductor regression covers CPU and CUDA")++ def dimensions(input):+ return (+ _constant_tensor([input.shape[-1] - 1, input.shape[-2] - 1], dtype=input.dtype).to(input) + input.sum()+ )++ compiled = torch_optimizer(dimensions, fullgraph=True, dynamic=True)+ for height, width in [(16, 19), (20, 23)]:+ input = torch.zeros(1, 1, height, width, device=device, dtype=dtype)+ self.assert_close(compiled(input), dimensions(input))+++class TestShearSamplerPlacement(BaseTester):+ @pytest.mark.parametrize("make_generator", [rg.ShearGenerator, partial(rg.AffineGenerator, 30.0)])+ @pytest.mark.parametrize("shear", [10.0, (-10.0, 10.0), (-10.0, 10.0, -5.0, 5.0)])+ def test_move(self, make_generator, shear, device, dtype):+ generator = make_generator(shear=shear).to(device=device, dtype=dtype)+ for sampler in (generator.shear_x_sampler, generator.shear_y_sampler):+ assert sampler.low.device == device+ assert sampler.low.dtype == dtype+ generator((4, 3, 16, 19))+++class TestLinearIlluminationPlacement(BaseTester):+ @pytest.mark.parametrize("generator_type", [rg.LinearIlluminationGenerator, rg.LinearCornerIlluminationGenerator])+ def test_moved_sampler(self, generator_type, device, dtype):+ generator = generator_type((0.1, 0.2), (-1.0, 1.0)).to(device=device, dtype=dtype)+ params = generator((4, 3, 16, 19))+ assert params["gradient"].device == torch.device("cpu")+ assert params["gradient"].dtype == torch.get_default_dtype()+++class TestResizedCropNumpyScale(BaseTester):+ def test_matches_tuple(self, device, dtype):+ tuple_generator = rg.ResizedCropGenerator((8, 9), (0.5, 1.0), (0.8, 1.2)).to(device=device, dtype=dtype)+ numpy_generator = rg.ResizedCropGenerator((8, 9), np.array([0.5, 1.0]), (0.8, 1.2)).to(+ device=device, dtype=dtype+ )+ torch.manual_seed(0)+ expected = tuple_generator((4, 3, 16, 19))+ torch.manual_seed(0)+ actual = numpy_generator((4, 3, 16, 19))+ for name, value in expected.items():+ self.assert_close(actual[name], value, rtol=0, atol=0)++ def test_dynamo(self, device, dtype, torch_optimizer):+ generator = rg.ResizedCropGenerator((8, 9), np.array([0.5, 1.0]), (0.8, 1.2)).to(device=device, dtype=dtype)+ src = torch_optimizer(lambda: generator((4, 3, 16, 19))["src"], fullgraph=True)()+ assert src.shape == (4, 4, 2)+ assert bool(((src[..., 0] >= 0) & (src[..., 0] <= 18) & (src[..., 1] >= 0) & (src[..., 1] <= 15)).all())+++class TestCenterCrop3DEmptyBatch(BaseTester):+ def test_matches_batched(self, device):+ empty = rg.center_crop_generator3d(0, 12, 16, 19, (6, 8, 9), device=device)+ batched = rg.center_crop_generator3d(1, 12, 16, 19, (6, 8, 9), device=device)+ for name, value in batched.items():+ assert empty[name].shape == (0, *value.shape[1:])+ assert empty[name].device == value.device+ assert empty[name].dtype == value.dtype++[email protected](not torch.cuda.is_available(), reason="Synchronization debugging requires CUDA")+class TestCudaParameterSync(BaseTester):+ @pytest.mark.parametrize(+ "make_generator",+ [+ pytest.param(lambda device: rg.AffineGenerator(torch.tensor([-30.0, 30.0], device=device)), id="affine"),+ pytest.param(lambda device: rg.PerspectiveGenerator(torch.tensor(0.5, device=device)), id="perspective"),+ ],+ )+ def test_no_host_device_sync(self, make_generator, device, dtype):+ if device.type != "cuda":+ pytest.skip("Synchronization debugging requires CUDA")+ generator = make_generator(device).to(device=device, dtype=dtype)+ generator((4, 3, 16, 19))+ torch.cuda.set_sync_debug_mode("error")+ try:+ generator((4, 3, 16, 19))+ finally:+ torch.cuda.set_sync_debug_mode("default")