π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): distance_transform reads masks clamped to [0, 1]; diamond_square seed not scaled by random_scale (#6045)
Dmytro Mishkin4330a6d44fa8
diff --git a/changelog.d/5964.fixed.md b/changelog.d/5964.fixed.mdindex 51b1ac326..d84505e94 100644--- a/changelog.d/5964.fixed.md+++ b/changelog.d/5964.fixed.md@@ -1 +1 @@-`kornia.contrib.diamond_square`, and so `RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow`, now generate an unbiased map. The seed divided its corners and centre by three, took the wrong corner for the right-edge midpoint and never interpolated the interior row-1 points of an elongated seed, and the square step at the border over-weighted a neighbour. A 9x9 map averaged 0.167 at the corners and the centre, 0.611 at columns 3 and 5 of the border rows and columns, and 0.39 to 0.48 in the interior (row 0: `[0.167, 0.503, 0.500, 0.611, 0.500, 0.611, 0.500, 0.503, 0.167]`), so a plasma brightness or shadow map darkened the corners and the centre of every image; the expected mean map is now a flat 0.5 for `torch.rand` with `random_scale=1` (other `random_scale` values still drift, see #5963), and an unnormalized map stays in [0, 1] for `torch.rand` when `random_scale` and `roughness` are in [0, 1]. The diamond and square centres are chosen by index parity, so a signed `random_fn` such as `torch.randn` no longer leaves most pixels at zero; a tensor `roughness` or `random_scale` follows the requested `dtype` and `device`; and an integer `normalize_range` such as `(0, 1)` is accepted. The random numbers are drawn in a different order, so a fixed seed gives a different map than before.+`kornia.contrib.diamond_square`, and so `RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow`, now generate an unbiased map. The seed divided its corners and centre by three, took the wrong corner for the right-edge midpoint and never interpolated the interior row-1 points of an elongated seed, and the square step at the border over-weighted a neighbour. A 9x9 map averaged 0.167 at the corners and the centre, 0.611 at columns 3 and 5 of the border rows and columns, and 0.39 to 0.48 in the interior (row 0: `[0.167, 0.503, 0.500, 0.611, 0.500, 0.611, 0.500, 0.503, 0.167]`), so a plasma brightness or shadow map darkened the corners and the centre of every image; the expected mean map is now a flat 0.5 for `torch.rand` with `random_scale=1`, and an unnormalized map stays in [0, 1] for `torch.rand` when `random_scale` and `roughness` are in [0, 1]. The diamond and square centres are chosen by index parity, so a signed `random_fn` such as `torch.randn` no longer leaves most pixels at zero; a tensor `roughness` or `random_scale` follows the requested `dtype` and `device`; and an integer `normalize_range` such as `(0, 1)` is accepted. The random numbers are drawn in a different order, so a fixed seed gives a different map than before.diff --git a/changelog.d/5978.added.md b/changelog.d/5978.added.mdindex 240fbc833..b882a88c9 100644--- a/changelog.d/5978.added.md+++ b/changelog.d/5978.added.md@@ -1 +1 @@-`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5963, #5967, #5968, #5977).+`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5967, #5968).diff --git a/changelog.d/6045.fixed.md b/changelog.d/6045.fixed.mdnew file mode 100644index 000000000..5c9b12a22--- /dev/null+++ b/changelog.d/6045.fixed.md@@ -0,0 +1,4 @@+Two corrections in `kornia.contrib`:++- `kornia.contrib.distance_transform` and `DistanceTransform` clamp the mask to [0, 1], so a mask with values above 1, such as 0/255, no longer collapses the result to all zeros: every value above 1 counts as a full source, and negative values as background. Mask values outside [0, 1] now get a zero gradient; they had one before, when the mask was used as given. Values in [0, 1], the bounds included, keep theirs.+- `kornia.contrib.diamond_square` with `random_scale` other than 1 no longer scales the seed by `random_scale`. The expected value is 0.5 at every pixel with `torch.rand`; it was 0.5Β·`random_scale` at the seed nodes and moved towards 0.5 level by level elsewhere (0.25 vs 0.31β0.35 at 0.5). `random_scale=1`, the default used by `RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow`, gives the same output as before. With `dtype=None`, a float64 tensor `roughness` now gives a float64 map at every size, as a float64 tensor `random_scale` already did; with only `roughness` in float64, a map with a side of 3 px or less came out float32 and a larger one float64.diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.pyindex a7eb67b43..fa3758335 100644--- a/kornia/contrib/diamond_square.py+++ b/kornia/contrib/diamond_square.py@@ -170,31 +170,32 @@ def diamond_square(- The map is grown on a :math:`2^n + 1` grid and cropped to ``output_size`` at its top-left corner, so it canbe a non-contiguous view. The seed is a :math:`3 \times K` grid, transposed to :math:`K \times 3` for a maptaller than wide, whose cell corners, the even nodes of its first and last rows (columns when transposed),- are ``random_scale`` times a ``random_fn`` draw, and whose other nodes are the means of their neighbours.+ are ``random_fn`` draws, and whose other nodes are the means of their neighbours.Each level sets a new node to:math:`(1 - s_k)\,\overline{n} + s_k\,u`, the mean :math:`\overline{n}` of its neighbours mixed with a- ``random_fn`` draw :math:`u` by :math:`s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k` at level- :math:`k \geq 1`: both are mixing weights, not amplitudes. A border node of the square step averages its- three neighbours; the diamond step's nodes are all interior, so its ``reflect`` padding never reaches them.+ ``random_fn`` draw :math:`u` by the weight :math:`s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k`+ at level :math:`k \geq 1`. ``random_scale`` and ``roughness`` act only through :math:`s_k`, a mixing+ weight, not an amplitude. A border node of the square step averages its three neighbours; the diamond+ step's nodes are all interior, so its ``reflect`` padding never reaches them.- ``random_fn`` is called as ``random_fn(shape, device=device, dtype=dtype)`` and is the only source ofrandomness, so ``functools.partial(torch.rand, generator=g)`` leaves the global generator alone. With``torch.rand`` the map stays in [0, 1] without normalization while ``random_scale`` and ``roughness`` are in- [0, 1], and with ``random_scale=1`` it is flat in mean (0.5 everywhere), though its variance varies across- the map.+ [0, 1], and it is flat in mean (0.5 at every pixel) for every ``random_scale``, though its variance varies+ across the map.- ``roughness`` and ``random_scale`` are a float, a 0-d tensor or a :math:`(B,)` tensor with one value per- sample, and follow ``device`` and ``dtype``.+ sample, and follow ``device`` and ``dtype``; with ``dtype=None`` a tensor keeps its dtype and a float takes+ the default dtype. When ``random_fn`` returns the dtype it is asked for, the map has the dtype that+ ``dtype`` (the default dtype for ``None``), ``roughness`` and ``random_scale`` promote to, at every map+ size. A ``random_fn`` that returns another dtype also promotes the levels' arithmetic to its dtype, but not+ a map with a side of 3 px or less, which is the seed alone and stores the draws in the requested dtype.- ``normalize_range=(min, max)`` rescales each :math:`(b, c)` plane to that range with:func:`~kornia.enhance.normalize_min_max`.- - Known defect: the mean is not flat when ``random_scale`` is neither 0 nor 1, ``roughness`` is non-zero and- both sides of the map exceed 3, so that it grows past its seed. The seed's mean is ``0.5 * random_scale`` and- every level mixes towards 0.5, so at ``random_scale=0.5`` the seed nodes average 0.25 and the other pixels- more, by an amount that depends on ``roughness`` and the map size: 0.31 to 0.35 on a :math:`9 \times 17` map- at the default ``roughness`` (`#5963 <https://github.com/kornia/kornia/issues/5963>`_).Args:output_size: a tuple of integers with the BxCxHxW of the image to be generated.roughness: the factor that scales the mixing weight at each recursion step.- random_scale: the mixing weight before the first recursion step, which also scales the seed.+ random_scale: scales the per-level mixing weight+ :math:`s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k`, :math:`k \geq 1`.random_fn: the callable function to use to sample a random torch.Tensor.normalize_range: if given, the ``(min, max)`` range each plane is min-max normalized to.device: the torch device to place the output map.@@ -235,15 +236,19 @@ def diamond_square(recursion_depth: int = int(min(math.log2(p2_width - 1) - 1, math.log2(p2_height - 1) - 1))seed_width: int = (p2_width - 1) // 2**recursion_depth + 1seed_height: int = (p2_height - 1) // 2**recursion_depth + 1- img: torch.Tensor = random_scale * _diamond_square_seed(- num_samples, seed_width, seed_height, random_fn, device, dtype- )+ seed = _diamond_square_seed(num_samples, seed_width, seed_height, random_fn, device, dtype)+ # The output dtype is that of the levels' arithmetic on the actual draws. Level 1 asks random_fn for the seed's+ # dtype promoted with random_scale's, and each level promotes the map with its draws and with+ # random_scale * roughness**k. A map that is the seed alone has no level, so it is promoted with roughness's dtype+ # after the loop; past the seed that promotion is already done and the cast is a no-op.+ img: torch.Tensor = seed.to(torch.promote_types(seed.dtype, random_scale.dtype))# perform recursionscale = random_scalefor _ in range(recursion_depth):scale = scale * roughnessimg = _one_diamond_one_square(img, scale, random_fn)+ img = img.to(torch.promote_types(img.dtype, roughness.dtype))# slice to match with the output sizeimg = img[..., :width, :height]diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.pyindex 7da9e8ea4..2208c8112 100644--- a/kornia/contrib/distance_transform.py+++ b/kornia/contrib/distance_transform.py@@ -127,7 +127,11 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)kernel = torch.exp(-dist / h).unsqueeze(0)out = torch.zeros_like(image, dtype=compute_dtype)- boundary = image.to(compute_dtype)+ # Clamp the mask to [0, 1] through torch.where, not torch.clamp: where passes gradient 1 at exactly 0 and 1 on+ # every torch version, while clamp's derivative at its bound is 1 on torch 2.5.1 and 2.9.1 and 0 on 2.14.+ boundary = torch.where(+ image > 1, torch.ones_like(image), torch.where(image < 0, torch.zeros_like(image), image)+ ).to(compute_dtype)signal_ones = torch.ones_like(boundary)can_stop = _can_stop_cascade(image)@@ -163,7 +167,10 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)kernel = torch.exp(-dist / h).unsqueeze(0)out = torch.zeros_like(image, dtype=compute_dtype)- boundary = image.to(compute_dtype)+ # The mask is clamped to [0, 1] through torch.where, as in 2-D.+ boundary = torch.where(+ image > 1, torch.ones_like(image), torch.where(image < 0, torch.zeros_like(image), image)+ ).to(compute_dtype)signal_ones = torch.ones_like(boundary)can_stop = _can_stop_cascade(image)@@ -192,14 +199,17 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3The transformation is applied independently across the channel dimension.Convention:- - The distance is to the nearest non-zero pixel, where SciPy's ``distance_transform_edt`` and OpenCV's+ - The distance is to the nearest positive pixel, where SciPy's ``distance_transform_edt`` and OpenCV's``distanceTransform`` measure it to the nearest zero: ``distance_transform(x)`` approximates- ``scipy.ndimage.distance_transform_edt(x == 0)``.- - ``image`` is a binary mask whose sources are the pixels equal to 1. A value :math:`0 < v < 1` is a weaker- source: it adds :math:`-h \log v` to a distance within ``kernel_size // 2`` of it whose window holds no- other source, less where the window holds one, as the soft minimum sums them before its logarithm, and- does not change the distances further away.- - A mask without any non-zero pixel gives 0 everywhere, as a full mask does, which keeps the output and its+ ``scipy.ndimage.distance_transform_edt(x <= 0)``, which is ``distance_transform_edt(x == 0)`` for a mask+ of 0 and 1.+ - ``image`` is a binary mask whose sources are the pixels equal to 1, read after clamping it to [0, 1]: a value+ above 1 is a full source, as 1 is, and a negative value is background, as 0 is. Values above 1 or below 0+ are clamped, so their gradient is 0, while values in [0, 1], the bounds included, pass the gradient+ through. A value :math:`0 < v < 1` is a weaker source: it adds :math:`-h \log v` to a distance within+ ``kernel_size // 2`` of it whose window holds no other source, less where the window holds one, as the+ soft minimum sums them before its logarithm, and does not change the distances further away.+ - A mask without any positive pixel gives 0 everywhere, as a full mask does, which keeps the output and itsgradient finite.- Known defect: the result is not Euclidean, and there is no general bound on its error(`#5956 <https://github.com/kornia/kornia/issues/5956>`_). From an isolated source it is exact only within@@ -209,9 +219,6 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3reached pixels share its window (replicate padding counts a pixel on the image border twice), the more thelarger ``h``: at the default ``h`` by 0.167 px beside a straight edge, 0.243 px midway between two sources2 px apart and 0.579 px in a one-pixel hole, and in a hole towards 0 as ``h`` nears its upper bound.- - Known defect: values above 1 are not rejected and change the distances; at the default ``kernel_size=3``- and ``h=0.35`` a mask of 0 and 255 gives 0 everywhere- (`#5977 <https://github.com/kornia/kornia/issues/5977>`_).Args:image: Image or volume with shape :math:`(B,C,H,W)` or :math:`(B,C,D,H,W)`.diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.pyindex a8494d9aa..1d3b4de65 100644--- a/tests/contrib/test_conv_distance_transformer.py+++ b/tests/contrib/test_conv_distance_transformer.py@@ -278,13 +278,50 @@ class TestConvDistanceTransform(BaseTester):self.assert_close(output1[0, 0, 0, 0, 0], expected_corner)def test_gradcheck(self, device):+ # 0.5, off the kink at 1 where the mask is clamped and a finite difference is one-sided.+ # On CUDA the backward of the cascade's convolutions and replicate padding is not deterministic: repeated+ # float64 backward passes differ by up to ~1e-15, which gradcheck's reentrancy check rejects at tolerance 0.+ nondet_tol = 1e-12 if device.type == "cuda" else 0.0B, C, H, W = 1, 1, 32, 32- sample2d = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- self.gradcheck(kornia.contrib.distance_transform, (sample2d,))+ sample2d = torch.full((B, C, H, W), 0.5, device=device, dtype=torch.float64, requires_grad=True)+ self.gradcheck(kornia.contrib.distance_transform, (sample2d,), nondet_tol=nondet_tol)B, C, D, H, W = 1, 1, 5, 5, 5- sample3d = torch.ones(B, C, D, H, W, device=device, dtype=torch.float64, requires_grad=True)- self.gradcheck(kornia.contrib.distance_transform, (sample3d,))+ sample3d = torch.full((B, C, D, H, W), 0.5, device=device, dtype=torch.float64, requires_grad=True)+ self.gradcheck(kornia.contrib.distance_transform, (sample3d,), nondet_tol=nondet_tol)++ @pytest.mark.parametrize(+ ("shape", "source", "neighbours"),+ [((1, 1, 4, 5), (1, 2), 8), ((1, 1, 3, 4, 5), (1, 1, 2), 26)],+ ids=["2d", "3d"],+ )+ def test_gradient_reaches_a_unit_source(self, shape, source, neighbours, device, dtype, cudnn_tf32_follows_option):+ # The mask is clamped to [0, 1] with torch.where, whose derivative at a value of exactly 1 is 1 on every torch+ # version; torch.clamp's is 0 there on torch 2.14 (AGENTS.md). Each neighbour of the interior source reads+ # -h * log(tap * v) in the first cascade step, so d/dv = -h / v = -0.35 per neighbour at v = 1, and nothing+ # later depends on v: the gradient at the source is 8 * -0.35 = -2.8 in 2-D and 26 * -0.35 = -9.1 in 3-D.+ sample = torch.zeros(*shape, device=device, dtype=dtype)+ sample[(0, 0, *source)] = 1.0+ sample.requires_grad_(True)+ kornia.contrib.distance_transform(sample).sum().backward()+ expected = torch.tensor(neighbours * -0.35, device=device, dtype=dtype)+ self.assert_close(sample.grad[(0, 0, *source)], expected)++ @pytest.mark.parametrize(+ ("shape", "above", "below"),+ [((1, 1, 4, 5), (1, 1), (2, 3)), ((1, 1, 3, 4, 5), (1, 1, 1), (1, 2, 3))],+ ids=["2d", "3d"],+ )+ def test_gradient_is_zero_outside_the_unit_range(self, shape, above, below, device, dtype):+ # Values above 1 or below 0 are clamped, so their gradient is 0; the pixels in [0, 1] still receive one.+ sample = torch.zeros(*shape, device=device, dtype=dtype)+ sample[(0, 0, *above)] = 2.0+ sample[(0, 0, *below)] = -1.0+ sample.requires_grad_(True)+ kornia.contrib.distance_transform(sample).sum().backward()+ assert sample.grad[(0, 0, *above)] == 0+ assert sample.grad[(0, 0, *below)] == 0+ assert (sample.grad != 0).any()@pytest.mark.parametrize("shape", [(1, 1, 4, 4), (1, 1, 4, 4, 4)], ids=["2d", "3d"])@pytest.mark.parametrize("has_signal", [False, True], ids=["all-zero", "one-hot"])@@ -545,17 +582,34 @@ class TestConvDistanceTransform(BaseTester):)self.assert_close(values, expected)- def test_wart_distance_transform_mask_above_one_5977(self, device, dtype):- # A source of value v contributes -h * log(v) instead of 0: at v = 2 its neighbour reads 1 - 0.35 * log(2)- # = 0.7574 instead of 1, and at v = 255 and the default kernel_size and h every pixel reads 0, as if on the- # foreground. A smaller h shrinks the shift: at h = 0.1 the neighbour reads 1 - 0.1 * log(255) = 0.4459.- image = torch.zeros(1, 1, 9, 13, device=device, dtype=dtype)- image[0, 0, 4, 6] = 1.0+ @pytest.mark.parametrize(+ ("shape", "source"), [((1, 1, 9, 13), (4, 6)), ((1, 1, 5, 7, 9), (2, 3, 4))], ids=["2d", "3d"]+ )+ def test_convention_values_above_one_are_full_sources(self, shape, source, device, dtype):+ # The mask is clamped to [0, 1], so a value above 1 is the same source as 1. Read unclamped, a source of value+ # v added -h * log(v) to the distances near it (its neighbour read 1 - 0.35 * log(2) = 0.7574 at v = 2), and+ # at v = 255 every pixel read 0.+ image = torch.zeros(*shape, device=device, dtype=dtype)+ image[(0, 0, *source)] = 1.0binary = kornia.contrib.distance_transform(image)- self.assert_close(binary[0, 0, 4, 7], torch.tensor(1.0, device=device, dtype=dtype))- doubled = kornia.contrib.distance_transform(2 * image)- self.assert_close(doubled[0, 0, 4, 7], torch.tensor(1.0 - 0.35 * math.log(2.0), device=device, dtype=dtype))- assert (kornia.contrib.distance_transform(255 * image) == 0).all()- small_h = kornia.contrib.distance_transform(255 * image, h=0.1)- self.assert_close(small_h[0, 0, 4, 7], torch.tensor(1.0 - 0.1 * math.log(255.0), device=device, dtype=dtype))- assert binary.max() > 5+ assert binary.max() > 3+ for v in (2.0, 20.0, 255.0):+ self.assert_close(kornia.contrib.distance_transform(v * image), binary, rtol=0, atol=0)+ assert (kornia.contrib.distance_transform(255 * image) != 0).any()++ @pytest.mark.parametrize(+ ("shape", "source", "negatives"),+ [((1, 1, 9, 13), (4, 6), [(4, 8), (0, 0)]), ((1, 1, 5, 7, 9), (2, 3, 4), [(2, 3, 6), (0, 0, 0)])],+ ids=["2d", "3d"],+ )+ def test_convention_negative_values_are_background(self, shape, source, negatives, device, dtype):+ # The mask is clamped to [0, 1], so a negative value is background. Read unclamped, in 2-D the -1 two pixels+ # from the source cancelled its contribution to the pixel between them, which read 2.17 instead of 1, and the+ # -1 and the -5 read 0 themselves, as did the -5's neighbours (float64, default kernel_size and h).+ image = torch.zeros(*shape, device=device, dtype=dtype)+ image[(0, 0, *source)] = 1.0+ negative = image.clone()+ negative[(0, 0, *negatives[0])] = -1.0+ negative[(0, 0, *negatives[1])] = -5.0+ dt = kornia.contrib.distance_transform+ self.assert_close(dt(negative), dt(image), rtol=0, atol=0)diff --git a/tests/contrib/test_diamond_square.py b/tests/contrib/test_diamond_square.pyindex 532cfd78b..9e9ab7126 100644--- a/tests/contrib/test_diamond_square.py+++ b/tests/contrib/test_diamond_square.py@@ -103,6 +103,119 @@ class TestDiamondSquare(BaseTester):assert out.dtype == torch.float32assert out.device.type == device.type+ @pytest.mark.parametrize("tensor_arg", ["random_scale", "roughness"])+ def test_dtype_none_follows_a_tensor_argument_at_every_size(self, tensor_arg, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ # With dtype=None each level promotes the map to the dtype of random_scale * roughness, and a map with a side+ # of 3 px or less, which is the seed alone, is cast to it too, without being scaled: it has the same dtype as+ # a larger one, and its values are the float32 draws.+ g = torch.Generator(device=device)+ draw = functools.partial(torch.rand, generator=g)+ value = torch.tensor(0.5, dtype=torch.float64)+ for size in ((1, 1, 2, 2), (1, 1, 3, 9), (2, 1, 9, 14)):+ g.manual_seed(0)+ out = kornia.contrib.diamond_square(size, random_fn=draw, device=device, **{tensor_arg: value})+ assert out.dtype == torch.float64+ if min(size[2:]) <= 3:+ g.manual_seed(0)+ ref = kornia.contrib.diamond_square(size, random_fn=draw, device=device, **{tensor_arg: 0.5})+ assert ref.dtype == torch.float32+ assert torch.equal(out, ref.double())++ @pytest.mark.parametrize(+ ("scale_f64", "roughness_f64", "expected"),+ [+ (False, False, [None, torch.float32, torch.float32]),+ (False, True, [None, torch.float32, torch.float64]),+ (True, False, [None, torch.float64, torch.float64]),+ (True, True, [None, torch.float64, torch.float64]),+ ],+ ids=["floats", "roughness-f64", "scale-f64", "both-f64"],+ )+ def test_dtype_none_draws_level_by_level_as_before(self, scale_f64, roughness_f64, expected, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ # random_fn is asked for the seed (dtype=None), then for each level in the dtype of the map entering it. The+ # unscaled seed enters level 1 promoted with random_scale's dtype only, as the seed scaled by random_scale did,+ # so each level draws in the same dtype, and random_scale=1 gives the same map. Expected sequences generated+ # on dd3bddb7e, where the seed was scaled by random_scale, with this recording random_fn and+ # kornia.contrib.diamond_square((2, 1, 9, 14), random_scale=s, roughness=r, random_fn=record)+ # for s = 1.0 or torch.tensor(1.0, dtype=torch.float64), r = 0.5 or torch.tensor(0.5, dtype=torch.float64).+ g = torch.Generator(device=device).manual_seed(0)+ asked = []++ def record(shape, device=None, dtype=None):+ asked.append(dtype)+ return torch.rand(shape, generator=g, device=device, dtype=dtype)++ scale = torch.tensor(1.0, dtype=torch.float64) if scale_f64 else 1.0+ roughness = torch.tensor(0.5, dtype=torch.float64) if roughness_f64 else 0.5+ out = kornia.contrib.diamond_square(+ (2, 1, 9, 14), roughness=roughness, random_scale=scale, random_fn=record, device=device+ )+ assert asked == expected+ assert out.dtype == expected[-1]++ @pytest.mark.parametrize(+ ("dtype", "drawn", "expected_dtype", "expected", "seed_only_dtype"),+ [+ (+ None,+ torch.float64,+ torch.float64,+ [+ [0.9700530171394348, 0.6190204124439906, 0.5825837657368917, 0.7164888574434708],+ [0.6135796297792718, 0.7338367893977338, 0.6909577292507927, 0.6741751155470027],+ ],+ torch.float32,+ ),+ (+ torch.float16,+ torch.float32,+ torch.float32,+ [+ [0.496337890625, 0.6477437019348145, 0.7212197780609131, 0.6671783924102783],+ [0.6196125149726868, 0.6749759912490845, 0.501835823059082, 0.5487739443778992],+ ],+ torch.float16,+ ),+ ],+ ids=["none-draws-f64", "f16-draws-f32"],+ )+ def test_random_fn_ignoring_dtype_gives_the_previous_map(+ self, dtype, drawn, expected_dtype, expected, seed_only_dtype, device+ ):+ if device.type != "cpu":+ pytest.skip("the literals are CPU values, and MPS has no float64")+ if dtype is not None and not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ # A random_fn that returns another dtype than it is asked for promotes the levels' arithmetic to its dtype,+ # so at random_scale=1 a map past its seed runs the operations of dd3bddb7e, where the seed was scaled by+ # random_scale, dtype included. Literals generated there on arm64 macOS, torch 2.14, with+ # g = torch.Generator().manual_seed(0)+ # draw = lambda shape, device=None, dtype=None: torch.rand(shape, generator=g, dtype=drawn)+ # out = kornia.contrib.diamond_square((1, 1, 9, 17), random_fn=draw, dtype=dtype)+ # out.dtype, out[0, 0, :2, :4]+ # They are not a cross-CPU bit pattern: torch 2.14 on x86 (the AMD EPYC CI runners, an Intel i7-14700K) rounds+ # the float32 levels' convolution at (1, 2) one ulp away, as a convolution accumulated in float64 does. A few+ # ulps of the output dtype still reject levels computed in the requested float16 (~1e-4 off) or a float64 map+ # computed in float32 (~1e-8 off).+ # A map that is the seed alone stores the draws in the requested dtype (dd3bddb7e: same dtype at (1, 1, 3, 9)).+ g = torch.Generator().manual_seed(0)++ def draw(shape, device=None, dtype=None):+ return torch.rand(shape, generator=g, device=device, dtype=drawn)++ out = kornia.contrib.diamond_square((1, 1, 9, 17), random_fn=draw, device=device, dtype=dtype)+ assert out.dtype == expected_dtype+ ulps = 4 * torch.finfo(expected_dtype).eps+ self.assert_close(+ out[0, 0, :2, :4], torch.tensor(expected, device=device, dtype=expected_dtype), rtol=0, atol=ulps+ )+ seed_only = kornia.contrib.diamond_square((1, 1, 3, 9), random_fn=draw, device=device, dtype=dtype)+ assert seed_only.dtype == seed_only_dtype+def test_integer_normalize_range(self, device, dtype):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")@@ -152,11 +265,13 @@ class TestDiamondSquare(BaseTester):pytest.skip("reflection_pad2d is unavailable for this device/dtype")# One level from a 3x5 seed: a new value is (1 - s) * mean(neighbours) + s * U, s = random_scale * roughness- # = 0.25, U = 1, seed corner draws [[1, 2, 4], [8, 16, 32]] scaled by random_scale. Worked by hand (scaled- # seed: corner 0.5, centre 3.375, top midpoint 1.625, left midpoint 2.625; diamond (1, 3) = 2.271484375):- # diamond (1, 1) = 0.75 * mean(0.5, 1.625, 2.625, 3.375) + 0.25 = 1.7734375- # border square (0, 1) = 0.75 * mean(0.5, 1.625, 1.7734375) + 0.25 = 1.224609375 (three neighbours)- # interior square (1, 2) = 0.75 * mean(1.625, 3.375, 1.7734375, 2.271484375) + 0.25 = 1.9459228515625+ # = 0.25, U = 1, seed corner draws [[1, 2, 4], [8, 16, 32]], not scaled by random_scale. Worked by hand (seed:+ # corner 1, centre (1 + 2 + 8 + 16) / 4 = 6.75, top midpoint 3.25, left midpoint 5.25, row-1 point between+ # the centres 9.5625 as in test_seed_values; diamond (1, 3) = 0.75 * mean(3.25, 2, 6.75, 9.5625) + 0.25 =+ # 4.29296875):+ # diamond (1, 1) = 0.75 * mean(1, 3.25, 5.25, 6.75) + 0.25 = 3.296875+ # border square (0, 1) = 0.75 * mean(1, 3.25, 3.296875) + 0.25 = 2.13671875 (three neighbours)+ # interior square (1, 2) = 0.75 * mean(3.25, 6.75, 3.296875, 4.29296875) + 0.25 = 3.548095703125def draw(shape, device=None, dtype=None):if shape[-2] == 2: # the seed's corner drawsreturn torch.tensor([[1.0, 2.0, 4.0], [8.0, 16.0, 32.0]], device=device, dtype=dtype).expand(shape)@@ -168,7 +283,7 @@ class TestDiamondSquare(BaseTester):assert out.shape == (5, 9)# seed corner, seed centre, level-1 diamond centre, border square centre, interior square centrenodes = torch.stack([out[0, 0], out[2, 2], out[1, 1], out[0, 1], out[1, 2]])- expected = torch.tensor([0.5, 3.375, 1.7734375, 1.224609375, 1.9459228515625], device=device, dtype=dtype)+ expected = torch.tensor([1.0, 6.75, 3.296875, 2.13671875, 3.548095703125], device=device, dtype=dtype)self.assert_close(nodes, expected)def test_convention_normalize_range_is_min_max_per_plane(self, device, dtype):@@ -199,19 +314,48 @@ class TestDiamondSquare(BaseTester):if accelerator_state is not None:assert torch.equal(accelerator_state, device_state())- def test_wart_mean_field_drifts_for_random_scale_not_one_5963(self, device, dtype):+ @pytest.mark.parametrize("random_scale", [0.25, 0.5, 1.0, 2.0])+ def test_convention_mean_field_is_flat_for_every_random_scale(self, random_scale, device, dtype):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")- # The map is linear in the draws, so a constant 0.5 draw gives the expected field of torch.rand exactly.- # With random_scale=0.5 the seed is 0.5 * 0.5 = 0.25, and each level mixes towards 0.5: a level-1 diamond is- # 0.75 * 0.25 + 0.25 * 0.5 = 0.3125, a level-1 square 0.328125 at the border and 0.3359375 inside.+ # The map is linear in the draws, so a constant 0.5 draw gives the expected field of torch.rand exactly. The+ # seed is the draws themselves (0.5) and each level computes (1 - s) * 0.5 + s * 0.5 = 0.5 for any s, so every+ # pixel is 0.5. A seed scaled by random_scale gave, at random_scale=0.5, 0.25 at the seed nodes, 0.3125 at+ # the level-1 diamonds and 0.328125 / 0.3359375 at the border / interior level-1 squares.def half(shape, device=None, dtype=None):return torch.full(shape, 0.5, device=device, dtype=dtype)out = kornia.contrib.diamond_square(- (1, 1, 9, 17), random_scale=0.5, random_fn=half, device=device, dtype=dtype- )[0, 0]- nodes = torch.stack([out[0, 0], out[4, 8], out[2, 2], out[0, 2], out[2, 4]])- expected = torch.tensor([0.25, 0.25, 0.3125, 0.328125, 0.3359375], device=device, dtype=dtype)- self.assert_close(nodes, expected)+ (1, 1, 9, 17), random_scale=random_scale, random_fn=half, device=device, dtype=dtype+ )+ self.assert_close(out, torch.full_like(out, 0.5))++ def test_random_scale_one_is_unchanged(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")++ # random_scale=1, the default and the value the plasma augmentations use, gives the same map whether or not+ # the seed is scaled by it. Draws come from a seeded CPU generator in float64 and are cast afterwards, so every+ # device and dtype sees the same numbers. Literal generated before the seed stopped being scaled:+ # g = torch.Generator().manual_seed(0)+ # draw = lambda shape, device=None, dtype=None: torch.rand(shape, generator=g, dtype=torch.float64).to(+ # device=device, dtype=dtype)+ # out = kornia.contrib.diamond_square((1, 1, 5, 9), random_scale=1.0, random_fn=draw, dtype=torch.float64)+ # out[0, 0, :3, :5]+ g = torch.Generator().manual_seed(0)++ def draw(shape, device=None, dtype=None):+ return torch.rand(shape, generator=g, dtype=torch.float64).to(device=device, dtype=dtype)++ out = kornia.contrib.diamond_square((1, 1, 5, 9), random_scale=1.0, random_fn=draw, device=device, dtype=dtype)+ expected = torch.tensor(+ [+ [0.9700530018065531, 0.5825837538768377, 0.8295946779397027, 0.5193563724418668, 0.707819864399788],+ [0.6392595145199516, 0.6425319703329853, 0.47735102570438287, 0.7140160159032599, 0.7129631915412449],+ [0.9005706178470932, 0.6569745561601958, 0.8109111676127666, 0.7014195097526202, 0.7036497142732241],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(out[0, 0, :3, :5], expected)