π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): normalize the half-precision meshgrid in float32 (#4231)
Logan Chu1751cdb15fce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da63bdf5e..2a2239468 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -269,6 +269,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0backward. The fallback is the input LAF when `preserve_orientation=True` and its upright form otherwise; a finitezero-scale input keeps its center and zero affine block.+* `create_meshgrid` and `create_meshgrid3d` return different normalized coordinates at `float16`+ and `bfloat16`. They used to evaluate `(xs / (size - 1) - 0.5) * 2` as three half-precision ops+ in eager, rounding after each, and to materialize the half ramp before the graph-capture branch+ widened it; `torch.compile` instead computed the chain in `float32` and rounded once, and folded+ the narrow-then-widen round trip away so that above `2 ** p` the two paths divided different+ numerators. A half-precision grid therefore changed the moment a model was wrapped in+ `torch.compile` -- by up to 0.0117 in the `[-1, 1]` range at `bfloat16` width 300 and 0.0156 at+ width 6000. A normalized half-precision grid is now built and normalized in `float32` and+ narrowed once, so eager, traced and compiled grids agree; the eager values move onto the+ correctly rounded side, which is the numeric change. `float32`, `float64` and integer grids and+ the pixel ramp are bit-for-bit unchanged, since none of them widen. On CUDA at `float16` up to+ one ulp of the coordinate dtype can still differ, because ATen's and triton's `float32` division+ are not bit-identical; `bfloat16` absorbs it and the CPU kernels agree exactly. The Linux CPU+ half-precision baselines move with it. `HomographyWarper` builds its precomputed grid in `float32`+ and its on-the-fly grid in the input dtype, and the two now agree, which fixes+ `test_homography_warper` at both dtypes and `test_translation[shape1]` at `float16`. At `bfloat16`+ `test_translation[shape0]` and `[shape2]` join the `shape1` and `shape3` entries already recorded:+ that test's `atol=1e-4` is out of reach for all four of its shapes there, and the two that passed+ did so only because the old grid's larger error round-tripped through `grid_sample`'s `bfloat16`+ unnormalize as an exact pixel index. Refs #4030. (#4231)+### Bug fixes* Reduce local-feature extraction overhead by accumulating orientation histograms directly,diff --git a/kornia/geometry/grid.py b/kornia/geometry/grid.pyindex 454308acf..ddf579919 100644--- a/kornia/geometry/grid.py+++ b/kornia/geometry/grid.py@@ -82,8 +82,18 @@ def create_meshgrid(# constant-folded by TorchScript's optimizing executor after the first run, which would freeze# the ramp at whatever the default dtype happened to be on that call.ramp_dtype = dtype if dtype is not None else torch.empty(0, device=device).dtype- xs = torch.arange(width, device=device, dtype=ramp_dtype)- ys = torch.arange(height, device=device, dtype=ramp_dtype)+ # Normalizing at float16/bfloat16 rounds three times in eager -- once per op in+ # ``(xs / (size - 1) - 0.5) * 2`` -- where inductor computes the chain in float32 and rounds+ # once on store. Eager also materializes the half ramp before the capture branch widens it,+ # while inductor folds that narrow-then-widen round trip away and keeps the exact index, so+ # above ``2 ** p`` the two paths were dividing different numerators. Running the whole+ # normalization in float32 and narrowing once removes both: the arithmetic is then the same+ # on every path and only the final rounding is left. float32/float64 and the pixel ramp are+ # bit-for-bit untouched, since neither widens.+ widened = normalized_coordinates and ramp_dtype in (torch.float16, torch.bfloat16)+ work_dtype = torch.float32 if widened else ramp_dtype+ xs = torch.arange(width, device=device, dtype=work_dtype)+ ys = torch.arange(height, device=device, dtype=work_dtype)# Fix TracerWarning# Note: keeping this formula inline avoids the extra tensors and shape checks incurred by# normalize_pixel_coordinates. The two paths use the same singleton-centre policy.@@ -94,30 +104,22 @@ def create_meshgrid(# return torch.unsqueeze(base_grid.transpose(0, 1), dim=0)if normalized_coordinates:if not torch.jit.is_scripting() and (torch.jit.is_tracing() or is_compiling()):- # Graph capture needs the tensor form to keep a symbolic size dynamic. Low-precision- # floating types cannot represent every practical image size exactly (e.g. bfloat16- # rounds 257 to 256 and 299 to 300), so the size arithmetic runs in float32. Divide- # against the *unrounded* divisor and round the quotient, which is what eager does- # against its Python-int divisor: casting the divisor down first would round it into- # the coordinate dtype, which eager never does.- work_dtype = torch.float32 if xs.dtype in (torch.float16, torch.bfloat16) else xs.dtype+ # Graph capture needs the tensor form to keep a symbolic size dynamic. The ramp is+ # already in ``work_dtype``, so the divisor is exact and the quotient no longer has+ # to be rounded back down mid-expression.width_t = torch.scalar_tensor(width, device=xs.device, dtype=work_dtype)height_t = torch.scalar_tensor(height, device=ys.device, dtype=work_dtype)- xs_norm = xs.to(work_dtype) / (width_t - 1)- ys_norm = ys.to(work_dtype) / (height_t - 1)- if xs.is_floating_point():- # A widened half type rounds back down here, which is exactly where eager rounds.- # An integral grid dtype must instead stay promoted into the default float, as the- # eager true-division leaves it.- xs_norm = xs_norm.to(xs.dtype)- ys_norm = ys_norm.to(ys.dtype)- xs = torch.where(width_t > 1, (xs_norm - 0.5) * 2, torch.zeros_like(xs_norm))- ys = torch.where(height_t > 1, (ys_norm - 0.5) * 2, torch.zeros_like(ys_norm))+ xs = torch.where(width_t > 1, (xs / (width_t - 1) - 0.5) * 2, xs * 0.0)+ ys = torch.where(height_t > 1, (ys / (height_t - 1) - 0.5) * 2, ys * 0.0)else:# ``* 0.0`` rather than ``zeros_like`` so that a singleton axis follows the# same integer-to-float promotion the non-singleton branch performs.xs = (xs / (width - 1) - 0.5) * 2 if width > 1 else xs * 0.0ys = (ys / (height - 1) - 0.5) * 2 if height > 1 else ys * 0.0+ if widened:+ # The single rounding, after the whole normalization.+ xs = xs.to(ramp_dtype)+ ys = ys.to(ramp_dtype)# generate grid by stacking coordinatesbase_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2@@ -158,34 +160,30 @@ def create_meshgrid3d(# float16/bfloat16, keeps the output length dynamic under export, and reads the default dtype# off a ``device``-bearing empty tensor so TorchScript cannot constant-fold the read.ramp_dtype = dtype if dtype is not None else torch.empty(0, device=device).dtype- xs = torch.arange(width, device=device, dtype=ramp_dtype)- ys = torch.arange(height, device=device, dtype=ramp_dtype)- zs = torch.arange(depth, device=device, dtype=ramp_dtype)+ # See ``create_meshgrid``: a normalized half-precision ramp is built and normalized in+ # float32 and narrowed once, so eager and captured grids agree.+ widened = normalized_coordinates and ramp_dtype in (torch.float16, torch.bfloat16)+ work_dtype = torch.float32 if widened else ramp_dtype+ xs = torch.arange(width, device=device, dtype=work_dtype)+ ys = torch.arange(height, device=device, dtype=work_dtype)+ zs = torch.arange(depth, device=device, dtype=work_dtype)# Fix TracerWarningif normalized_coordinates:if not torch.jit.is_scripting() and (torch.jit.is_tracing() or is_compiling()):- # See ``create_meshgrid``: low-precision dtypes round large sizes, so the size- # arithmetic runs in float32 and the quotient, not the divisor, is what gets cast down.- work_dtype = torch.float32 if xs.dtype in (torch.float16, torch.bfloat16) else xs.dtypewidth_t = torch.scalar_tensor(width, device=xs.device, dtype=work_dtype)height_t = torch.scalar_tensor(height, device=ys.device, dtype=work_dtype)depth_t = torch.scalar_tensor(depth, device=zs.device, dtype=work_dtype)- xs_norm = xs.to(work_dtype) / (width_t - 1)- ys_norm = ys.to(work_dtype) / (height_t - 1)- zs_norm = zs.to(work_dtype) / (depth_t - 1)- if xs.is_floating_point():- # As in ``create_meshgrid``: round a widened half type back down, but leave an- # integral grid dtype promoted into the default float.- xs_norm = xs_norm.to(xs.dtype)- ys_norm = ys_norm.to(ys.dtype)- zs_norm = zs_norm.to(zs.dtype)- xs = torch.where(width_t > 1, (xs_norm - 0.5) * 2, torch.zeros_like(xs_norm))- ys = torch.where(height_t > 1, (ys_norm - 0.5) * 2, torch.zeros_like(ys_norm))- zs = torch.where(depth_t > 1, (zs_norm - 0.5) * 2, torch.zeros_like(zs_norm))+ xs = torch.where(width_t > 1, (xs / (width_t - 1) - 0.5) * 2, xs * 0.0)+ ys = torch.where(height_t > 1, (ys / (height_t - 1) - 0.5) * 2, ys * 0.0)+ zs = torch.where(depth_t > 1, (zs / (depth_t - 1) - 0.5) * 2, zs * 0.0)else:xs = (xs / (width - 1) - 0.5) * 2 if width > 1 else xs * 0.0ys = (ys / (height - 1) - 0.5) * 2 if height > 1 else ys * 0.0zs = (zs / (depth - 1) - 0.5) * 2 if depth > 1 else zs * 0.0+ if widened:+ xs = xs.to(ramp_dtype)+ ys = ys.to(ramp_dtype)+ zs = zs.to(ramp_dtype)# generate grid by stacking coordinatesbase_grid = torch.stack(torch.meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3return base_grid.permute(0, 2, 1, 3).unsqueeze(0) # 1xDxHxWx3diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex f533e3f85..987c559d4 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -502,12 +502,11 @@ call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCropBycall builtins.AssertionError tests/geometry/transform/test_elastic_transform.py::TestElasticTransform::test_values[cpu-bfloat16]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-1]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-3]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-bfloat16-1]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-bfloat16-2]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-bfloat16-3]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-bfloat16-1]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-bfloat16-3]+call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape0]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape1]+call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape2]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape3]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestGetPerspectiveTransform::test_back_and_forth[cpu-bfloat16]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90[cpu-bfloat16]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 7b378a659..d53282d38 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -492,12 +492,8 @@ call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCentercall builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-float16-crop_size2]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-1]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-3]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-float16-1]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-float16-2]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_homography_warper[cpu-float16-3]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-float16-1]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-float16-3]-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-float16-shape1]call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-float16-shape3]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90_batch[cpu-float16]diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.pyindex 4e707b488..fc65808bb 100644--- a/tests/geometry/test_grid.py+++ b/tests/geometry/test_grid.py@@ -297,6 +297,46 @@ def test_pixel_meshgrid_half_dtype_matches_compile(is_3d, grid_dtype):assert_close(actual, expected, atol=0.0, rtol=0.0)[email protected]("grid_dtype", [torch.float16, torch.bfloat16])[email protected]("is_3d", [False, True], ids=["2d", "3d"])+def test_normalized_meshgrid_half_dtype_matches_compile(is_3d, grid_dtype, device):+ """A half-precision normalized grid must not change when it is built under ``torch.compile``.++ Eager evaluates ``(xs / (size - 1) - 0.5) * 2`` as three half-precision ops and rounds after+ each; inductor computes the chain in float32 and rounds once on store. Eager also materializes+ the half ramp before the capture branch widens it, while inductor folds that narrow-then-widen+ round trip away and keeps the exact index, so above ``2 ** p`` the two divided different+ numerators. Building and normalizing the ramp in float32 and narrowing once removes both, and+ is a no-op at float32/float64, which never widen.++ The sizes are the first at which the pixel ramps themselves diverge, so the normalized error+ on top of them is the one under test. At float16 on CUDA a residue of at most one ulp of the+ coordinate dtype survives, because ATen's and triton's float32 division are not bit-identical;+ bfloat16's 8-bit significand absorbs it and the CPU kernels agree exactly.+ """++ class MeshGrid(torch.nn.Module):+ def forward(self, image):+ if is_3d:+ return kornia.geometry.create_meshgrid3d(+ image.shape[-3], image.shape[-2], image.shape[-1], True, device=image.device, dtype=image.dtype+ )+ return kornia.geometry.create_meshgrid(+ image.shape[-2], image.shape[-1], True, device=image.device, dtype=image.dtype+ )++ size = 300 if grid_dtype == torch.bfloat16 else 3000+ shape = (1, 1, 2, 2, size) if is_3d else (1, 1, 2, size)+ image = torch.zeros(*shape, dtype=grid_dtype, device=device)++ expected = MeshGrid()(image)+ actual = torch.compile(MeshGrid(), fullgraph=True)(image)++ assert actual.dtype == expected.dtype == grid_dtype+ inexact_division = device.type == "cuda" and grid_dtype == torch.float16+ assert_close(actual, expected, atol=torch.finfo(grid_dtype).eps if inexact_division else 0.0, rtol=0.0)++def test_create_meshgrid3d(device, dtype):depth, height, width = 5, 4, 6normalized_coordinates = False