π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): register RenderingDeFMO's times as a buffer so .to() moves it (#4319)
tritsystem078bfcc36c97
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38db3dba3..dea7b2b07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -351,6 +351,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering+ time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never+ moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so+ `RenderingDeFMO().half()` left `times` at `float32` and the first forward raised `RuntimeError: Input+ type (torch.FloatTensor) and weight type (torch.HalfTensor) should be the same`. `times` is now a+ non-persistent buffer (it is fully determined by `tsr_steps`, not learned, so `state_dict()` keys and+ existing checkpoints are unaffected), and `forward` casts into a local variable rather than depending+ on the caller having matched dtype. Same bug shape as #4069/#4079 in a different class; the normal+ `float32` path is byte-identical to before. (#4319)* `jpeg_codec_differentiable` no longer returns an all-`NaN` image at `jpeg_quality=0`, a value inside the`[0, 100]` range it documents and validates. `_jpeg_quality_to_scale` divides `5000` by the quality on the`< 50` branch, which is `inf` at `0`, and the polynomial floor of `inf` is `NaN`, poisoning the image and@@ -377,7 +386,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* `distance_transform` no longer returns NaN gradients when the cascade's convolution is exactly zero, includingsparse masks and all-zero inputs; the existing forward output is unchanged. (#4232)-* `SemanticSegmentation.visualize` works for CUDA, MPS and half-precision models. It indexed theCPU-drawn colormap with the mask's `argmax`, which raises for CUDA and MPS masks, and recognised asoftmax head with `torch.allclose(sum, 1)` at float32-sized default tolerances, which a float16 ordiff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex dc90d815c..4c8a1d2d8 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -339,7 +339,12 @@ class RenderingDeFMO(nn.Module):nn.Conv2d(4, 4, kernel_size=3, stride=1, padding=1, bias=True),)self.net = model- self.times = torch.linspace(0, 1, self.tsr_steps)+ # `times` is fully determined by `tsr_steps` (derived state, not learned) --+ # register as a non-persistent buffer so `.to()` / `.cuda()` / `.half()` move+ # it through the normal nn.Module machinery instead of leaving it behind as a+ # plain attribute. persistent=False keeps state_dict() keys unchanged, same+ # rationale/convention as #4079 (SIFTDescriptor.gk et al.).+ self.register_buffer("times", torch.linspace(0, 1, self.tsr_steps), persistent=False)def forward(self, latent: torch.Tensor) -> torch.Tensor:"""Render a temporal RGBA sequence from latent DeFMO features.@@ -352,7 +357,10 @@ class RenderingDeFMO(nn.Module):Tensor with shape :math:`(B, T, 4, H_{out}, W_{out})`, where ``T`` is thenumber of rendered time steps and 4 represents RGBA channels."""- times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1)+ # cast into a local rather than relying on the caller having matched dtype --+ # `.to()` already moved `self.times` to the module's own device/dtype, this+ # additionally covers a mismatched-precision `latent` without mutating self.+ times = self.times.to(dtype=latent.dtype, device=latent.device).unsqueeze(0).repeat(latent.shape[0], 1)renders = []for ki in range(times.shape[1]):t_tensor = (diff --git a/tests/feature/test_defmo.py b/tests/feature/test_defmo.pyindex 30ea672fa..fa5d71c91 100644--- a/tests/feature/test_defmo.py+++ b/tests/feature/test_defmo.py@@ -19,10 +19,73 @@ import pytestimport torchfrom kornia.feature import DeFMO+from kornia.feature.defmo import RenderingDeFMOfrom testing.base import BaseTester+class TestRenderingDeFMOTimesBuffer(BaseTester):+ """`times` must be a real buffer so `.to()` moves it, and `forward` must not rebind it.++ Same bug shape as #4069/#4079 (SIFTDescriptor.gk et al.) in a different class: `times`+ was a plain Python attribute, invisible to `Module.to()`/`.half()`, and `forward`+ compensated by re-deriving its DEVICE (but never its dtype) from the input on every+ call -- so `.half()` a module and calling it crashed with a dtype-mismatch RuntimeError.+ """++ def test_to_moves_times(self, device):+ # float16 rather than the default float32, or the dtype assertion would hold+ # vacuously; float16 also works on MPS, where float64 is unavailable.+ mod = RenderingDeFMO().to(device, torch.float16)+ assert mod.times.dtype == torch.float16+ assert mod.times.device == torch.empty(0, device=device).device++ def test_times_stays_out_of_state_dict(self, device):+ # non-persistent: `times` is fully determined by `tsr_steps`, not learned, so+ # existing checkpoints keep loading with strict=True.+ assert "times" not in RenderingDeFMO().state_dict()++ def test_forward_does_not_mutate_the_module(self, device):+ mod = RenderingDeFMO().to(device).eval()+ before = (mod.times.dtype, mod.times.device)+ latent = torch.rand(1, 2048, 4, 4, device=device)+ with torch.no_grad():+ mod(latent)+ assert (mod.times.dtype, mod.times.device) == before++ @pytest.mark.slow+ def test_half_precision_forward_no_longer_crashes(self, device):+ # the actual reported defect: .half() left `times` at float32 (only device was+ # ever re-derived in forward, never dtype), so a half-precision forward crashed+ # with "Input type ... and weight type ... should be the same".+ mod = RenderingDeFMO().to(device, torch.float16).eval()+ latent = torch.rand(1, 2048, 4, 4, device=device, dtype=torch.float16)+ with torch.no_grad():+ out = mod(latent)+ assert out.dtype == torch.float16++ def test_matches_pre_fix_output_in_the_normal_float32_path(self, device):+ # behaviour-preserving: pinned against the pre-fix module (plain `self.times`+ # attribute, `.to(latent.device)`-only) with the same seed and input -- confirmed+ # byte-identical (torch.equal) locally before this value was hardcoded here.+ # A tight absolute tolerance doesn't survive kornia's own CI matrix, though:+ # different torch versions/BLAS backends on "cpu" still reorder the Bottleneck+ # blocks' float32 accumulation differently (observed 201292.0 vs 201291.984375,+ # a ~1.6e-8 relative difference -- ordinary floating-point non-associativity, not+ # a behavioral change). rel=1e-3 keeps ~1000x margin above that while still+ # catching a real regression, which would produce a very different value.+ if device.type != "cpu":+ pytest.skip("checksum pinned on CPU; cross-device float summation can differ further")+ torch.manual_seed(0)+ mod = RenderingDeFMO().to(device).eval()+ latent = torch.rand(1, 2048, 4, 4, device=device)+ with torch.no_grad():+ out = mod(latent)+ assert out.shape == (1, 24, 4, 64, 64)+ assert out.dtype == torch.float32+ assert out.sum().item() == pytest.approx(201291.984375, rel=1e-3)++class TestDeFMO(BaseTester):@pytest.mark.slowdef test_shape(self, device, dtype):