Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): draw RandomRain's integer ranges uniformly over their closed bounds (#4568)

Dmytro Mishkinfc1bcb394afa
diff --git a/changelog.d/4568.fixed.md b/changelog.d/4568.fixed.md
new file mode 100644
index 000000000..9ff23210c
--- /dev/null
+++ b/changelog.d/4568.fixed.md
@@ -0,0 +1,7 @@
+`RandomRain` now draws `number_of_drops`, `drop_height` and `drop_width` uniformly over their closed integer
+ranges. The upper bound used to be practically unreachable (`drop_height=(5, 20)` gave 5 to 19) and a signed
+`drop_width` drew `0` twice as often as any other value (#4567). Seeded draws therefore differ from earlier
+releases, and because the upper bounds are drawn now, an image that only cleared the old effective maximum can
+raise the documented drop-size check: on the defaults, a 20-row or 5-column image raises on some seeds where it
+never did before. A range that is reversed, fractional or non-finite is rejected at construction instead of
+reaching the sampler.
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index 6b57d99a1..cdacbcb6e 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -61,15 +61,14 @@ class RandomRain(IntensityAugmentationBase2D):
the last column of the image are never painted unless the drop is exactly one short of the image
on that axis; a single-pixel drop never reaches the last two rows. Tracked in
`#4604 <https://github.com/kornia/kornia/issues/4604>`_.
- - the drawn sizes and drop count are float draws truncated toward zero, so unless the range is a single
- point, a positive upper bound is practically never drawn: the default ``drop_height=(5, 20)`` gives
- heights of ``5`` to ``19`` (an image shorter than 20 pixels raises on some seeds, and on every seed when
- it is 5 pixels tall or shorter). A negative ``drop_width`` bound rounds toward zero instead: a negative
- lower bound is practically never drawn while a non-positive upper bound is, and a range from ``-1`` or
- below to ``1`` or above draws ``0`` twice as often as any other value -- or practically always at
- ``(-1, 1)`` exactly, where only an exact ``-1.0`` draw, one ``float32`` value in ``2**24``, escapes
- the truncation to ``0``. Tracked in `#4567
- <https://github.com/kornia/kornia/issues/4567>`_.
+ - the three integer ranges are closed and uniform: every integer from the lower to the upper bound
+ is drawn with the same probability, so the default ``drop_height=(5, 20)`` reaches ``20``, the
+ default ``drop_width=(-5, 5)`` reaches ``-5`` and ``5``, and ``0`` carries no more weight than
+ any other width. Both upper bounds are live against the size rule above, which they were not
+ when they were practically never drawn: with the defaults an image 20 pixels tall, or 5 pixels
+ wide, now raises on some seeds -- and on every seed once it is 5 pixels tall or shorter, where
+ no drawable height is legal. A range that is reversed, fractional or non-finite raises
+ ``ValueError`` at construction.
- ``same_on_batch=True`` gives every sample of the batch the same drop count, the same drop size and
the same coordinates; left at ``False`` each sample draws its own.
@@ -80,7 +79,7 @@ class RandomRain(IntensityAugmentationBase2D):
>>> rain(input)
tensor([[[[0.4963, 0.7843, 0.0885, 0.1320, 0.3074],
[0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
- [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
+ [0.3489, 0.4017, 0.7843, 0.1689, 0.2939],
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.py
index 1c364d038..b36ceeb8b 100644
--- a/kornia/augmentation/random_generator/_2d/random_rain.py
+++ b/kornia/augmentation/random_generator/_2d/random_rain.py
@@ -17,6 +17,8 @@
from __future__ import annotations
+from typing import Union
+
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
@@ -24,6 +26,44 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core.utils import _extract_device_dtype
+def _closed_integer_range(
+ value: Union[tuple[int, int], list[int], torch.Tensor], name: str, device: torch.device
+) -> torch.Tensor:
+ """Return the half-open sampler bounds ``[lo, hi + 1)`` for a closed integer range ``(lo, hi)``."""
+ if isinstance(value, torch.Tensor):
+ value = tuple(value.flatten().tolist())
+ if not isinstance(value, (tuple, list)) or len(value) != 2:
+ raise ValueError(f"`{name}` must be a (lower, upper) pair. Got {value}.")
+ lower, upper = value
+ # Whole numbers only. This is also what disposes of ``nan`` and ``inf``, which are neither greater
+ # nor smaller than the other bound and would sail through an ordering test into the sampler, and of
+ # a fractional pair, which the clamp below draws worse than the truncation it replaces:
+ # ``(0.5, 2.5)`` covers ``[0.5, 3.5)``, and folding the ``3`` back onto ``2.5`` leaves the cast to
+ # ``torch.long`` to truncate it to ``2``, which then takes half the draws against a quarter before.
+ if not (float(lower).is_integer() and float(upper).is_integer()):
+ raise ValueError(f"`{name}` must be a pair of whole numbers. Got {value}.")
+ if lower > upper:
+ raise ValueError(f"`{name}`[0] should be smaller than or equal to `{name}`[1]. Got {value}.")
+ # Built on ``device`` explicitly: a bare ``torch.tensor`` follows an ambient ``torch.set_default_device``
+ # instead, which allocates the bounds on that device and, under a ``meta`` one, cannot move them back.
+ return torch.tensor([float(lower), float(upper) + 1.0], device=device)
+
+
+def _draw_closed_integer(
+ batch_size: int, sampler: UniformDistribution, same_on_batch: bool, device: torch.device
+) -> torch.Tensor:
+ """Draw one integer per sample, uniformly over the closed range ``sampler`` was built from.
+
+ ``floor``, not a truncating cast: truncation rounds toward zero, so a signed range such as
+ ``drop_width=(-5, 5)`` would fold ``(-1, 0)`` and ``(0, 1)`` onto ``0`` and draw it twice as often as
+ any other value. The clamp removes the excluded end point: ``lo + u * (hi + 1 - lo)`` rounds up onto
+ ``hi + 1`` in ``float32`` for the largest draw ``u = 1 - 2 ** -24`` (``5 + u * 16`` is exactly
+ ``21.0``), which ``floor`` would keep, so about one draw in ``2 ** 24`` would leave the closed range.
+ """
+ drawn = _adapted_rsampling((batch_size,), sampler, same_on_batch).floor()
+ return drawn.clamp(max=sampler.high - 1).to(device=device, dtype=torch.long)
+
+
class RainGenerator(RandomGeneratorBase):
def __init__(
self, number_of_drops: tuple[int, int], drop_height: tuple[int, int], drop_width: tuple[int, int]
@@ -38,24 +78,11 @@ class RainGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- number_of_drops = _range_bound(
- self.number_of_drops,
- "number_of_drops",
- center=self.number_of_drops[0] / 2 + self.number_of_drops[1] / 2,
- bounds=(self.number_of_drops[0], self.number_of_drops[1] + 1),
- ).to(device)
- drop_height = _range_bound(
- self.drop_height,
- "drop_height",
- center=self.drop_height[0] / 2 + self.drop_height[1] / 2,
- bounds=(self.drop_height[0], self.drop_height[1] + 1),
- ).to(device)
- drop_width = _range_bound(
- self.drop_width,
- "drop_width",
- center=self.drop_width[0] / 2 + self.drop_width[1] / 2,
- bounds=(self.drop_width[0], self.drop_width[1] + 1),
- ).to(device)
+ # Each range is a closed integer interval: the sampler covers ``[lo, hi + 1)`` and ``forward``
+ # floors the draw, so every integer from ``lo`` to ``hi`` is drawn with the same probability.
+ number_of_drops = _closed_integer_range(self.number_of_drops, "number_of_drops", device)
+ drop_height = _closed_integer_range(self.drop_height, "drop_height", device)
+ drop_width = _closed_integer_range(self.drop_width, "drop_width", device)
drop_coordinates = _range_bound((0, 1), "drops_coordinate", center=0.5, bounds=(0, 1)).to(
device=device, dtype=dtype
@@ -69,16 +96,9 @@ class RainGenerator(RandomGeneratorBase):
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.drop_width, self.drop_height, self.number_of_drops])
- # self.ksize_factor.expand((batch_size, -1))
- number_of_drops_factor = _adapted_rsampling((batch_size,), self.number_of_drops_sampler, same_on_batch).to(
- device=_device, dtype=torch.long
- )
- drop_height_factor = _adapted_rsampling((batch_size,), self.drop_height_sampler, same_on_batch).to(
- device=_device, dtype=torch.long
- )
- drop_width_factor = _adapted_rsampling((batch_size,), self.drop_width_sampler, same_on_batch).to(
- device=_device, dtype=torch.long
- )
+ number_of_drops_factor = _draw_closed_integer(batch_size, self.number_of_drops_sampler, same_on_batch, _device)
+ drop_height_factor = _draw_closed_integer(batch_size, self.drop_height_sampler, same_on_batch, _device)
+ drop_width_factor = _draw_closed_integer(batch_size, self.drop_width_sampler, same_on_batch, _device)
coordinates_factor = _adapted_rsampling(
(batch_size, int(number_of_drops_factor.max().item()) if number_of_drops_factor.numel() > 0 else 0, 2),
self.coordinates_sampler,
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index ce0e0261c..f0ebf5de7 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5569,6 +5569,14 @@ class TestRandomRain(BaseTester):
assert (aug._params["drop_width_factor"] == aug._params["drop_width_factor"][0]).all()
self.assert_close(aug._params["coordinates_factor"][0], aug._params["coordinates_factor"][1])
+ def test_construction_ignores_the_ambient_default_device(self):
+ # The sampler bounds are built on the generator's own device. A bare `torch.tensor` follows
+ # `torch.set_default_device` instead, which puts them on the ambient device and then moves them
+ # straight back -- and under a `meta` context the move raises `Cannot copy out of meta tensor`.
+ with torch.device("meta"):
+ aug = RandomRain(p=1.0, drop_height=(2, 3), drop_width=(2, 3), number_of_drops=(1, 3))
+ assert aug._param_generator.drop_height_sampler.high.device == torch.device("cpu")
+
class TestMultiprocessing:
torch.manual_seed(0) # for random reproductibility
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index e6a7bf2fe..35ad41bf0 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -377,9 +377,11 @@ class TestBlurConventions(BaseTester):
# Issue #4599: `kernel_size` is drawn once per SAMPLE and then one entry -- the one at a uniformly
# drawn `_params["idx"]`, not the first -- is applied to the whole batch; and because the draw is
# `UniformDistribution(ks[0] // 2, ks[1] // 2)` truncated with `.int()`, the range's upper bound is
- # practically never reached. `(3, 5)` is therefore a constant 3 -- "practically": as for RandomRain
- # below, the float32 draw rounds onto the bound about once in 2**24 (seed 204 draws one 5 in 50000),
- # so the pin is that the bound is vanishingly rare, not impossible.
+ # practically never reached. `(3, 5)` is therefore a constant 3 -- "practically": the float32 draw
+ # rounds onto the bound about once in 2**24 (seed 204 draws one 5 in 50000), so the pin is that the
+ # bound is vanishingly rare, not impossible. RandomRain had the same wart and no longer does
+ # (#4567): it draws over `[lo, hi + 1)`, floors, and clamps that rounding escape back onto the closed
+ # range -- the remedy this one still needs.
# Snippet used to generate expected:
# import collections
# for ks in ((3, 5), (3, 7), (5, 11)):
@@ -1023,44 +1025,97 @@ class TestNoiseAndWeatherConventions(BaseTester):
aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(1, 1), drop_width=(width, width), p=1.0)
assert int((aug(image) != 0).sum()) == 1
- # Issue #4567: the three integer ranges are float draws truncated to integers, and the generator's
- # `hi + 1` shift goes through the `bounds` argument that `_range_bound` ignores for a tuple, so the
- # upper bound is never drawn and a signed `drop_width` truncates both `(-1, 0)` and `(0, 1)` to 0.
+ # The three integer ranges are closed and uniform (the fix for #4567: the sampler covers
+ # ``[lo, hi + 1)``, the draw is floored and then clamped to ``hi``, where a truncating cast of a
+ # ``[lo, hi)`` draw used to skip the upper bound and fold ``(-1, 0)`` and ``(0, 1)`` onto ``0``).
# Snippet used to generate expected:
# torch.manual_seed(0)
# p = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
- # p = p.forward_parameters((20000, 1, 64, 64))
+ # p = p.forward_parameters((22000, 1, 64, 64))
# for k in ("number_of_drops_factor", "drop_height_factor", "drop_width_factor"):
- # print(k, collections.Counter(p[k].flatten().tolist()))
- # executed 2026-09-15 (torch 2.14.0, cpu) -> drops `{2: 9939, 3: 10061}`, heights `5..19` (about
- # 1333 each, no 20), widths `-4..4` with `0: 4075` against about 2000 for every other value.
+ # print(k, sorted(collections.Counter(p[k].flatten().tolist()).items()))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> drops 2..4 (7298, 7349, 7353), heights 5..20 (1301 to
+ # 1455) and widths -5..5 (1906 to 2090), every count within 6% of the uniform expectation (7333,
+ # 1375 and 2000). The pin allows 15%, not 10%: the 16-bin height is the tight one, where 22000
+ # draws put 10% at 3.8 sigma and 1 of seeds 0..99 exceeds it (max deviation 10.7%), against 5.7
+ # sigma and 0 of 100 at 15%. What the tolerance has to separate is a factor of two, not a few
+ # percent -- truncation gave `0` twice its share -- so the wider band loses no mutation.
@pytest.mark.device_agnostic
- def test_wart_random_rain_upper_bound_is_never_drawn_4567(self):
+ def test_convention_random_rain_integer_ranges_are_closed_and_uniform(self):
torch.manual_seed(_FORWARD_SEED)
aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
- params = aug.forward_parameters((20000, 1, 64, 64))
- drops = params["number_of_drops_factor"].flatten()
- heights = params["drop_height_factor"].flatten()
- widths = params["drop_width_factor"].flatten()
- # "Practically never", not never: `lo + (hi - lo) * u` with u = 1 - 2**-24 rounds onto `hi` in
- # float32 for the top handful of the 2**24 representable draws, so over 20000 draws the bound
- # appears with probability about 0.2% per seed -- seed 80 draws a 4 here. The pin is that the
- # bound is vanishingly rare, not that it is impossible; the lower bound is always drawn.
- assert int(drops.min()) == 2 and int(drops.max()) <= 4 and int((drops == 4).sum()) < 5
- assert int(heights.min()) == 5 and int(heights.max()) <= 20 and int((heights == 20).sum()) < 5
- assert int(widths.min()) == -4 and int(widths.max()) <= 5 and int((widths == 5).sum()) < 5
- zeros, ones = int((widths == 0).sum()), int((widths == 1).sum())
- assert zeros > 1.5 * ones and ones > 1000
- # Truncation is toward zero, so on a range below zero it is the lower bound that is not drawn and
- # the upper bound that is: `(-5, -1)` draws -4..-1 (about 5000 each out of 20000) and `(-3, 0)`
- # draws -2..0, so 0 is not doubled there.
- for bounds, expected in (((-5, -1), (-4, -1)), ((-3, 0), (-2, 0))):
- torch.manual_seed(_FORWARD_SEED)
- aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(1, 1), drop_width=bounds, p=1.0)
- drawn = aug.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
- assert (int(drawn.min()), int(drawn.max())) == expected
- counts = torch.stack([(drawn == value).sum() for value in range(expected[0], expected[1] + 1)])
- assert float(counts.max()) < 1.2 * float(counts.min())
+ params = aug.forward_parameters((22000, 1, 64, 64))
+ for key, low, high in (
+ ("number_of_drops_factor", 2, 4),
+ ("drop_height_factor", 5, 20),
+ ("drop_width_factor", -5, 5),
+ ):
+ drawn = params[key].flatten()
+ assert drawn.dtype == torch.long
+ assert (int(drawn.min()), int(drawn.max())) == (low, high), key
+ counts = torch.bincount(drawn - low, minlength=high - low + 1)
+ expected = drawn.numel() / (high - low + 1)
+ assert bool(((counts > 0.85 * expected) & (counts < 1.15 * expected)).all()), (key, counts.tolist())
+
+ # The excluded end point of the half-open sampler range is clamped back, not drawn: for the largest
+ # value `torch.rand` can return, `lo + u * (hi + 1 - lo)` rounds up onto `hi + 1` in float32
+ # (`5 + (1 - 2 ** -24) * 16` is exactly `21.0`), which `floor` would keep -- about one draw in 2**24,
+ # and a `drop_height` of 21 makes the forward raise on a 21-row image where 20 is legal.
+ # Snippet used to generate expected: the same three ranges, with `torch.rand` patched to return
+ # `1 - 2 ** -24` everywhere.
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `[4, 20, 5]` with the clamp, `[5, 21, 5]` without it.
+ @pytest.mark.device_agnostic
+ def test_convention_random_rain_largest_draw_stays_inside_the_closed_range(self, monkeypatch):
+ largest = 1 - 2**-24
+ real_rand = torch.rand
+ monkeypatch.setattr(torch, "rand", lambda *args, **kwargs: torch.full_like(real_rand(*args, **kwargs), largest))
+ aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
+ params = aug.forward_parameters((4, 1, 64, 64))
+ # The patch has to reach the generator's own draws, or the pin below is vacuous: the coordinate
+ # sampler runs over [0, 1], so under the patch every coordinate is exactly the patched value.
+ assert float(params["coordinates_factor"].min()) == largest
+ assert params["number_of_drops_factor"].tolist() == [4, 4, 4, 4]
+ assert params["drop_height_factor"].tolist() == [20, 20, 20, 20]
+ assert params["drop_width_factor"].tolist() == [5, 5, 5, 5]
+
+ # A reversed range is rejected at construction, where the samplers are built -- on each of the three
+ # parameters, not only the one a single example would name.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("name", ["number_of_drops", "drop_height", "drop_width"])
+ def test_convention_random_rain_rejects_a_reversed_range(self, name):
+ ranges = {"number_of_drops": (1, 1), "drop_height": (1, 1), "drop_width": (1, 1)}
+ ranges[name] = (6, 5)
+ with pytest.raises(ValueError, match=name):
+ K.RandomRain(p=1.0, **ranges)
+
+ # The ranges are integer ranges, so a bound that is not a whole number is rejected at construction
+ # too -- including `nan` and `inf`, which an ordering test alone does not catch (they are neither
+ # greater nor smaller than the other bound, so `drop_height=(nan, 5)` used to reach the sampler and
+ # draw a silent `0`), and a fractional pair, which the clamp draws more unevenly than the truncation
+ # it replaces: `(0.5, 2.5)` gave `{0: 25%, 1: 50%, 2: 25%}` and would give `{0: 17%, 1: 33%, 2: 50%}`.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("bounds", [(0.5, 2.5), (1, 2.5), (float("nan"), 5), (5, float("nan")), (1, float("inf"))])
+ @pytest.mark.parametrize("name", ["number_of_drops", "drop_height", "drop_width"])
+ def test_convention_random_rain_rejects_a_fractional_or_non_finite_range(self, name, bounds):
+ ranges = {"number_of_drops": (1, 1), "drop_height": (1, 1), "drop_width": (1, 1)}
+ ranges[name] = bounds
+ with pytest.raises(ValueError, match=name):
+ K.RandomRain(p=1.0, **ranges)
+ # Integral floats are the same range written another way, and stay accepted.
+ ranges[name] = (1.0, 2.0)
+ K.RandomRain(p=1.0, **ranges)
+
+ # The pair itself is validated: a range that is not two values, whatever its length, is rejected
+ # rather than silently indexed, and a tensor range is accepted as the old `_range_bound` accepted it.
+ @pytest.mark.device_agnostic
+ def test_convention_random_rain_validates_the_range_pair(self):
+ for bad in ((1, 2, 3), (1,), 5):
+ with pytest.raises(ValueError, match="drop_height"):
+ K.RandomRain(p=1.0, drop_height=bad)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(p=1.0, number_of_drops=(1, 1), drop_height=torch.tensor([2, 4]), drop_width=(1, 1))
+ drawn = aug.forward_parameters((2000, 1, 64, 64))["drop_height_factor"]
+ assert sorted(set(drawn.flatten().tolist())) == [2, 3, 4]
# Issue #4604: the start coordinate is scaled by `H - h - 1`, so the last row and column are never
# painted unless the drop is one short of the image on that axis. Literal seeds, as for the other
@@ -1093,10 +1148,11 @@ class TestNoiseAndWeatherConventions(BaseTester):
# aug = K.RandomRain(number_of_drops=(1, 50), drop_height=(1, 3), drop_width=(1, 3), p=1.0,
# same_on_batch=sob)
# aug(torch.zeros(4, 1, 12, 30)); print(sob, aug._params["number_of_drops_factor"].tolist())
- # executed 2026-09-15 (torch 2.14.0, cpu) -> `True [25, 25, 25, 25]` and `False [25, 38, 5, 7]`.
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `True [25, 25, 25, 25]` and `False [25, 39, 5, 7]`.
def test_convention_random_rain_same_on_batch_draws_one_drop_count(self, device, dtype):
- # B is 16, not 4: `drop_height=(1, 3)` truncates to {1, 2}, so "the unshared draw differs across
- # the batch" is a `2 * 2 ** -B` event -- 29 of seeds 0..199 coincide at B=4, 3 at B=8 and none
+ # B is 16, not 4: `drop_height=(1, 3)` and `drop_width=(1, 3)` each draw from {1, 2, 3}, so
+ # "the unshared draw differs across the batch" fails when one of the two factors comes out
+ # constant, a `2 * 3 ** -(B - 1)` event -- 16 of seeds 0..199 coincide at B=4, 1 at B=8 and none
# at B=16.
batch_size = 16
image = torch.zeros(batch_size, 1, 12, 30, device=device, dtype=dtype)
@@ -1316,28 +1372,29 @@ class TestNoiseAndWeatherConventions(BaseTester):
with pytest.raises(error, match=match):
_sync(factories[name]()(image).device)
- # The degenerate signed range: `(-1, 1)` satisfies the block's "draws 0 twice as often as any other
- # value" but has no other value to be twice as often as -- truncation toward zero maps the whole
- # interval onto 0, except an exact -1.0 draw (rand returning 0.0, one float32 value in 2**24, which a
- # 2**20 batch at seed 1 does produce), so the pin is "practically always", as for the upper bounds.
+ # The degenerate signed range `(-1, 1)` is where the old truncation toward zero was total: it mapped
+ # the whole interval onto `0`, except an exact `-1.0` draw (#4567). A closed uniform draw gives the
+ # three values equal weight, and `0` stops carrying its neighbours' weight one step wider too.
# Snippet used to generate expected:
- # g = RainGenerator(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-1, 1))
- # torch.manual_seed(0); print(set(g((40000, 3, 64, 64))["drop_width_factor"].flatten().tolist()))
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `{0}`, against `{-1, 0, 1}` for `(-2, 2)`.
+ # for bounds in ((-1, 1), (-2, 2)):
+ # g = RainGenerator(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=bounds)
+ # torch.manual_seed(0)
+ # print(bounds, sorted(Counter(g((20000, 3, 64, 64))["drop_width_factor"].flatten().tolist()).items()))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `{-1: 6688, 0: 6776, 1: 6536}` and, for `(-2, 2)`,
+ # `{-2: 3941, -1: 4083, 0: 4075, 1: 3976, 2: 3925}`.
@pytest.mark.device_agnostic
- def test_convention_random_rain_symmetric_unit_width_range_is_constant_zero(self):
- torch.manual_seed(_FORWARD_SEED)
- degenerate = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-1, 1), p=1.0)
- drawn = degenerate.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
- assert set(drawn.tolist()) <= {-1.0, 0.0}
- assert float((drawn == 0).float().mean()) > 0.999
- # One step wider and the doubling the block describes is visible again.
- torch.manual_seed(_FORWARD_SEED)
- wider = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-2, 2), p=1.0)
- widths = wider.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
- assert set(widths.tolist()) == {-1.0, 0.0, 1.0}
- zeros, ones = int((widths == 0).sum()), int((widths == 1).sum())
- assert zeros > 1.5 * ones
+ def test_convention_random_rain_symmetric_signed_width_range_is_uniform(self):
+ # `(-5, -1)` and `(-3, 0)` come from the wart pin this replaces: on a range that never crosses
+ # zero, truncation toward zero drops the LOWER bound instead of the upper, so they are the cases
+ # where `floor` and the old cast differ and a half-fixed draw would still show.
+ for low, high in ((-1, 1), (-2, 2), (-5, -1), (-3, 0)):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(low, high), p=1.0)
+ drawn = aug.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
+ assert sorted(set(drawn.tolist())) == list(range(low, high + 1))
+ counts = torch.bincount(drawn - low, minlength=high - low + 1)
+ expected = drawn.numel() / (high - low + 1)
+ assert bool(((counts > 0.9 * expected) & (counts < 1.1 * expected)).all()), ((low, high), counts.tolist())
class TestIlluminationAndNormalizeConventions(BaseTester):