#5052·kornia

Crop generators cast the start draw to the parameter dtype before truncating: a float64 augmentation or a half `size`/`scale` tensor puts crop starts one past the last valid position

Author: ducha-aikiCreated Sep 28, 2026Updated Sep 28, 2026

CropGenerator, CropGenerator3D and (through CropGenerator.forward) ResizedCropGenerator compute each start as floor(u.to(param_dtype) * (W - w + 1)). Here u is the Uniform(0, 1) draw in the sampler dtype, and param_dtype comes from the constructor arguments: float32 unless a tensor size, scale or ratio was passed. When param_dtype is narrower than the draw, the cast rounds draws just below 1 up to exactly 1.0, and the start lands one past the last valid position. This happens on every backend, CPU included. It is the rounding #4553's suggested fix warned about ("casting a float32 draw to half before truncating would bring the rounding back"). #4553 and #5050 left this path out of scope.

Measured on main 95ea672cd, torch 2.14.0, CPU, 8 × 2^16 rows of 8×8 inputs, size-4 crop (a row counts if either axis is out of range):

case out-of-range rows
CropGenerator(torch.full((B, 2), 4.0, dtype=float16)), augmentation float32 237 / 524 288
same, size in bfloat16 2013 / 524 288
RandomResizedCrop((4, 4), scale=torch.tensor([0.25, 0.25], dtype=float16), ratio=(1, 1)), float32 243 / 524 288
CropGenerator((4, 4)) with the generator moved to float64 (float64 draw cast to float32 size) 6 / 100 663 296 (about 2^-25 per axis draw)

After #5050 (the sampler is float32 for half augmentations), a half size tensor combined with a half augmentation dtype also shows 237 (f16) and 2013 (bf16) per 2^19 on CPU. On main that combination gave 0, because the half draw never reaches 1.0 on CPU.

PatchMixGenerator floors in the draw dtype and is not affected. RandomRainGenerator clamps to high - 1 for the same reason (see its comment about one draw in 2^24).

Options.

  1. Multiply and floor in the draw dtype (or torch.promote_types(u.dtype, diff.dtype)), then cast the integer start to the parameter dtype. Integer starts are exact in float16 up to 2048 and in bfloat16 up to 256, so the cast after the floor cannot round past the limit in that range. For a float64 augmentation with float32 size, this changes a few seeded float64 starts, not only the out-of-range ones.
  2. Clamp the start to diff - 1 after the floor, as RandomRainGenerator does. This works on any path and keeps every in-range start bitwise identical. It moves the rare 1.0 draws onto the last position (bias about 2^-12 / 2^-9 / 2^-25).

Pin: a CPU-only test with a half size tensor and 2^16 draws fails on main (about 30 out-of-range rows expected for float16).

Posted on behalf of @ducha-aiki by Claude (Opus 5.5).