π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix float16 descriptor normalization across direct and LAF calls (#5842)
Hanzheng Wangb07645c9b203
diff --git a/changelog.d/5842.fixed.md b/changelog.d/5842.fixed.mdnew file mode 100644index 000000000..062ed4f4a--- /dev/null+++ b/changelog.d/5842.fixed.md@@ -0,0 +1 @@+Keep pretrained `SOSNet` and `HyNet` float16 descriptors accurate, called directly or through `get_laf_descriptors` and `LAFDescriptor`, by preserving final BatchNorm statistics and avoiding overflow in filter response normalization. `FilterResponseNorm2d` now computes bfloat16 inputs in float32 too, which brings pretrained `HyNet` bfloat16 descriptors closer to float32. Convert models to float16 before scripting them.diff --git a/kornia/feature/_normalization.py b/kornia/feature/_normalization.pynew file mode 100644index 000000000..77fac236b--- /dev/null+++ b/kornia/feature/_normalization.py@@ -0,0 +1,69 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from collections import OrderedDict+from collections.abc import Callable++import torch+from torch import nn+++class _DescriptorSequential(nn.Sequential):+ """Keep a descriptor's final BatchNorm statistics and computation in float32 for half inputs."""++ def __init__(self, *args: nn.Module | OrderedDict[str, nn.Module]) -> None:+ super().__init__(*args)+ # Sequential slices share modules. Only the original descriptor's final norm is protected;+ # a slice ending at an earlier BatchNorm must not change that shared layer's dtype.+ if (+ len(self)+ and isinstance(self[-1], nn.BatchNorm2d)+ and not (len(args) == 1 and isinstance(args[0], OrderedDict))+ ):+ self[-1]._descriptor_float32_statistics = True+ for module in self:+ if getattr(module, "_descriptor_float32_statistics", False):+ for name in ("running_mean", "running_var"):+ tensor = getattr(module, name)+ if tensor is not None and tensor.dtype == torch.float16:+ setattr(module, name, tensor.float())++ def _apply(self, fn: Callable[[torch.Tensor], torch.Tensor], recurse: bool = True) -> "_DescriptorSequential":+ statistics = tuple(+ tensor+ for module in self+ if getattr(module, "_descriptor_float32_statistics", False)+ for tensor in (module.running_mean, module.running_var)+ )++ def convert(tensor: torch.Tensor) -> torch.Tensor:+ converted = fn(tensor)+ if converted.dtype == torch.float16 and any(tensor is statistic for statistic in statistics):+ # Recover from the original buffer: promoting an already-overflowed value cannot restore it.+ return tensor.to(device=converted.device, dtype=torch.float32)+ return converted++ return super()._apply(convert, recurse=recurse)++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ for module in self:+ if getattr(module, "_descriptor_float32_statistics", False) and input.dtype == torch.float16:+ # MPS also requires the input and running statistics to have the same dtype.+ input = module(input.float()).to(input.dtype)+ else:+ input = module(input)+ return inputdiff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex 198136f13..36e4cb68a 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -22,6 +22,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.download import hf_url, load_state_dict_from_url+from kornia.feature._normalization import _DescriptorSequentialurls: Dict[str, str | list[str]] = {}urls["liberty"] = [@@ -115,6 +116,12 @@ class FilterResponseNorm2d(nn.Module):Returns:Normalized tensor with the same shape as the input."""+ input_dtype = x.dtype+ half = input_dtype in (torch.float16, torch.bfloat16)+ if half:+ # Pretrained HyNet produces activations whose squares exceed the float16 range, and its scale and bias+ # cancel too many bits for either half dtype.+ x = x.float()# Compute the mean norm of activations per channel.nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)@@ -126,6 +133,10 @@ class FilterResponseNorm2d(nn.Module):x = self.weight * xif self.is_bias:x = x + self.bias+ if half:+ # Scale and bias stay in float32 too: in pretrained HyNet they cancel (weight 3.70, bias -3.40 in the+ # first layer), so rounding before them loses several bits.+ x = x.to(torch.promote_types(input_dtype, self.eps.dtype))return x@@ -206,6 +217,10 @@ class HyNet(nn.Module):- Input: :math:`(B, 1, 32, 32)`- Output: :math:`(B, 128)`+ Note:+ With float16 weights, the final BatchNorm keeps its running statistics in float32.+ Convert the model to float16 before calling ``torch.jit.script``.+Examples:>>> input = torch.rand(16, 1, 32, 32)>>> hynet = HyNet()@@ -265,7 +280,7 @@ class HyNet(nn.Module):TLU(128),)- self.layer7 = nn.Sequential(+ self.layer7 = _DescriptorSequential(nn.Dropout(self.drop_rate),nn.Conv2d(128, self.dim_desc, kernel_size=8, bias=False),nn.BatchNorm2d(self.dim_desc, affine=False),diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex a384dae2e..d07c43ca0 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -88,20 +88,29 @@ def _run_descriptor(module: nn.Module, patches: torch.Tensor) -> torch.Tensor:module, which that API refuses, in the slots of a copy of the module. The cast is differentiable, so gradientsreach the module's own parameters. Eager calls, ``torch.compile`` and ``torch.export`` take the same path. Everysubmodule is switched to eval for the call and its ``training`` flag is restored afterwards.+ Descriptor statistics marked for float32 computation retain that precision for float16 patches."""modes = [m.training for m in module.modules()]module.eval()try:tensors = list(itertools.chain(module.named_parameters(), module.named_buffers()))- needs_cast = any(- t.device != patches.device or (t.is_floating_point() and t.dtype != patches.dtype) for _, t in tensors- )+ float32_statistics: set[str] = set()+ if patches.dtype == torch.float16:+ for prefix, child in module.named_modules():+ if getattr(child, "_descriptor_float32_statistics", False):+ float32_statistics.update(+ f"{prefix}.{name}" if prefix else name for name in ("running_mean", "running_var")+ )++ def target_dtype(name: str, tensor: torch.Tensor) -> torch.dtype:+ if name in float32_statistics:+ return torch.float32+ return patches.dtype if tensor.is_floating_point() else tensor.dtype++ needs_cast = any(t.device != patches.device or t.dtype != target_dtype(name, t) for name, t in tensors)if not needs_cast:return module(patches)- state = {- name: t.to(device=patches.device, dtype=patches.dtype) if t.is_floating_point() else t.to(patches.device)- for name, t in tensors- }+ state = {name: t.to(device=patches.device, dtype=target_dtype(name, t)) for name, t in tensors}if not isinstance(module, torch.jit.ScriptModule):return torch.func.functional_call(module, state, (patches,))# functional_call refuses a TorchScript module, so the cast tensors go into the slots of a copy instead; they@@ -133,6 +142,7 @@ def get_laf_descriptors(``img`` for the call (a TorchScript module is called on a cast copy). The module keeps its device, dtype andparameters, every submodule is switched to eval for the call and gets its train/eval mode back afterwards, andgradients reach the module's parameters.+ SOSNet and HyNet retain their final BatchNorm statistics in float32 for float16 images.Args:img: image features with shape :math:`(B,C,H,W)`.diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 3aceaf1c5..c3354e927 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -22,6 +22,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.download import hf_url, load_state_dict_from_url+from kornia.feature._normalization import _DescriptorSequentialurls: Dict[str, str | list[str]] = {}urls["lib"] = [@@ -47,6 +48,10 @@ class SOSNet(nn.Module):- Input: :math:`(B, 1, 32, 32)`- Output: :math:`(B, 128)`+ Note:+ With float16 weights, the final BatchNorm keeps its running statistics in float32.+ Convert the model to float16 before calling ``torch.jit.script``.+Examples:>>> input = torch.rand(8, 1, 32, 32)>>> sosnet = SOSNet()@@ -58,7 +63,7 @@ class SOSNet(nn.Module):def __init__(self, pretrained: bool = False) -> None:super().__init__()- self.layers = nn.Sequential(+ self.layers = _DescriptorSequential(nn.InstanceNorm2d(1, affine=False),nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),nn.BatchNorm2d(32, affine=False),diff --git a/tests/feature/test_descriptor_normalization.py b/tests/feature/test_descriptor_normalization.pynew file mode 100644index 000000000..520c7d6bf--- /dev/null+++ b/tests/feature/test_descriptor_normalization.py@@ -0,0 +1,246 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import copy++import pytest+import torch++from kornia.feature import FilterResponseNorm2d, HyNet, LAFDescriptor, SOSNet, get_laf_descriptors+from kornia.feature._normalization import _DescriptorSequential+from kornia.feature.laf import extract_patches_from_pyramid, laf_from_center_scale_ori++from testing.base import BaseTester+++class TestDescriptorNormalization(BaseTester):+ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ @pytest.mark.parametrize("model_dtype", [torch.float32, torch.float16])+ def test_dynamo_laf_descriptor(self, device, torch_optimizer, model_cls, model_dtype):+ model = model_cls().to(device)+ norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]+ norm.running_var.fill_(1e5)+ model.to(model_dtype)+ wrapped = LAFDescriptor(model)+ img = torch.rand(1, 1, 48, 48, device=device, dtype=torch.float16)+ lafs = laf_from_center_scale_ori(+ torch.tensor([[[20.0, 20.0]]], device=device, dtype=img.dtype),+ torch.full((1, 1, 1, 1), 8.0, device=device, dtype=img.dtype),+ )+ self.assert_close(torch_optimizer(wrapped)(img, lafs), wrapped(img, lafs))++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ def test_default_half_dtype(self, device, model_cls):+ default_dtype = torch.get_default_dtype()+ try:+ torch.set_default_dtype(torch.float16)+ with torch.device(device):+ model = model_cls()+ finally:+ torch.set_default_dtype(default_dtype)+ norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]+ assert norm.running_var.dtype == torch.float32+ norm.running_var.fill_(1e5)+ out = model(torch.rand(2, 1, 32, 32, device=device, dtype=torch.float16))+ assert out.dtype == torch.float16+ assert torch.isfinite(out).all()++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ @pytest.mark.parametrize("model_dtype", [torch.float32, torch.float16])+ @pytest.mark.parametrize("scripted", [False, True])+ def test_laf_descriptor_half_statistics(self, device, model_cls, model_dtype, scripted):+ model = model_cls().to(device)+ norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]+ norm.running_var.copy_(torch.linspace(1e5, 5e6, norm.num_features, device=device))+ model = model.to(model_dtype)+ reference = copy.deepcopy(model).half().eval()+ if scripted:+ model = torch.jit.script(model)+ model.train()+ before = {name: tensor.clone() for name, tensor in model.state_dict().items()}+ modes = [layer.training for layer in model.modules()]+ img = torch.rand(1, 1, 48, 48, device=device, dtype=torch.float16)+ lafs = laf_from_center_scale_ori(+ torch.tensor([[[20.0, 20.0], [30.0, 30.0]]], device=device, dtype=img.dtype),+ torch.full((1, 2, 1, 1), 8.0, device=device, dtype=img.dtype),+ )+ patches = extract_patches_from_pyramid(img, lafs, 32).reshape(2, 1, 32, 32)+ expected = reference(patches).reshape(1, 2, -1)+ actual = LAFDescriptor(model)(img, lafs)+ self.assert_close(actual, expected)+ assert actual.dtype == img.dtype+ # Averaging keeps the loss gradient representable for the tiny, untrained descriptors.+ actual.float().mean().backward()+ expected.float().mean().backward()+ assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in model.parameters())+ assert all(p.grad is None or torch.isfinite(p.grad).all() for p in model.parameters())+ for parameter, ref_parameter in zip(model.parameters(), reference.parameters()):+ if parameter.grad is not None:+ # Both gradients are computed in float16, so compare them at float16 tolerance even when the model+ # keeps float32 parameters.+ self.assert_close(parameter.grad.to(ref_parameter.grad.dtype), ref_parameter.grad)+ with pytest.warns(UserWarning, match="LAF contains no keypoints"):+ empty = get_laf_descriptors(img, lafs[:, :0], model)+ assert empty.shape == (1, 0, 128)+ assert empty.dtype == img.dtype+ assert modes == [layer.training for layer in model.modules()]+ for name, tensor in model.state_dict().items():+ self.assert_close(tensor, before[name], rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ @pytest.mark.parametrize("convert", ["half", "to"])+ def test_half_preserves_running_statistics(self, device, model_cls, convert):+ model = model_cls().to(device)+ norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]+ # The published SOSNet and HyNet checkpoints contain variances up to 1.2e5 and 5.3e6.+ norm.running_var.copy_(torch.linspace(1e5, 5e6, norm.num_features, device=device))+ norm.running_mean.fill_(100.0)+ reference = copy.deepcopy(norm)+ reference_model = copy.deepcopy(model)+ state_keys = set(model.state_dict())++ model = model.half() if convert == "half" else model.to(dtype=torch.float16)+ assert set(model.state_dict()) == state_keys+ self.assert_close(norm.running_var, reference.running_var, rtol=0.0, atol=0.0)+ self.assert_close(norm.running_mean, reference.running_mean, rtol=0.0, atol=0.0)+ patches = torch.rand(2, 1, 32, 32, device=device)+ self.assert_close(model(patches.half()), reference_model(patches.half().float()).half())+ model.half().float()+ self.assert_close(norm.running_var, reference.running_var, rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("is_eps_learnable", [False, True])+ def test_frn_large_half_activations(self, device, dtype, is_eps_learnable):+ layer = FilterResponseNorm2d(2, is_eps_leanable=is_eps_learnable).to(device, dtype)+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32+ reference = copy.deepcopy(layer).to(reference_dtype)+ # These magnitudes occur inside pretrained HyNet for ordinary [0, 1] image patches.+ x = torch.tensor([256.0, -512.0, 1024.0, -2048.0], device=device, dtype=dtype)+ x = x.repeat(2).reshape(1, 2, 2, 2).requires_grad_()+ ref_x = x.detach().to(reference_dtype).requires_grad_()+ actual = layer(x)+ expected = reference(ref_x)+ self.assert_close(actual, expected.to(dtype))+ actual.flatten()[0].backward()+ expected.flatten()[0].backward()+ # Compare gradients at unit scale so the dtype's absolute tolerance cannot hide zero gradients.+ self.assert_close(x.grad * 2048, ref_x.grad.to(dtype) * 2048)+ self.assert_close(layer.weight.grad, reference.weight.grad.to(dtype))+ self.assert_close(layer.bias.grad, reference.bias.grad.to(dtype))+ if is_eps_learnable:+ self.assert_close(layer.eps.grad, reference.eps.grad.to(dtype))++ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16], ids=["float16", "bfloat16"])+ def test_frn_scale_and_bias_cancel_in_float32(self, device, half):+ # Pretrained HyNet's first FilterResponseNorm2d has weight 3.70 and bias -3.40, so on a nearly flat patch+ # `weight * x + bias` cancels most of its leading bits. Only the final rounding to the half dtype may remain.+ layer = FilterResponseNorm2d(1).to(device)+ with torch.no_grad():+ layer.weight.fill_(3.7035257816314697)+ layer.bias.fill_(-3.4002184867858887)+ layer = layer.to(half)+ x = torch.linspace(0.9, 1.0, 64, device=device).reshape(1, 1, 8, 8).to(half)+ expected = copy.deepcopy(layer).cpu().double()(x.cpu().double())+ actual = layer(x)+ assert actual.dtype == half+ self.assert_close(actual.cpu().double(), expected, rtol=torch.finfo(half).eps, atol=0.0)++ @pytest.mark.parametrize("is_scale,is_bias", [(False, False), (False, True), (True, False), (True, True)])+ def test_frn_mixed_dtype(self, device, dtype, is_scale, is_bias):+ layer = FilterResponseNorm2d(2, is_scale=is_scale, is_bias=is_bias).to(device, dtype)+ x = torch.tensor([256.0, -512.0, 1024.0, -2048.0], device=device, dtype=torch.float16)+ x = x.repeat(2).reshape(1, 2, 2, 2)+ expected_dtype = torch.promote_types(x.dtype, dtype)+ reference = copy.deepcopy(layer).to(torch.float64 if dtype == torch.float64 else torch.float32)+ expected = reference(x.to(reference.eps.dtype)).to(expected_dtype)+ actual = layer(x)+ assert actual.dtype == expected_dtype+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ def test_half_load_state_dict(self, device, model_cls):+ source = model_cls().to(device)+ norm = [layer for layer in source.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]+ norm.running_var.fill_(1e5)+ target = model_cls().to(device).half()+ target.load_state_dict(source.state_dict(), strict=True)+ source.half()+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float16)+ self.assert_close(target(patches), source(patches), rtol=0.0, atol=0.0)+ restored = model_cls().to(device).half()+ restored.load_state_dict(target.state_dict(), strict=True)+ self.assert_close(restored(patches), target(patches), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("training", [True, False])+ @pytest.mark.parametrize("momentum", [0.1, None])+ def test_final_batchnorm_state_and_gradients(self, device, training, momentum):+ model = _DescriptorSequential(torch.nn.Identity(), torch.nn.BatchNorm2d(2, affine=False, momentum=momentum))+ model = model.to(device).train(training)+ model[-1].running_var.fill_(1e5)+ reference = copy.deepcopy(model)+ model.half()+ x = torch.tensor([256.0, -512.0, 1024.0, -2048.0], device=device, dtype=torch.float16)+ x = x.repeat(4).reshape(2, 2, 2, 2).requires_grad_()+ ref_x = x.detach().float().requires_grad_()+ for _ in range(2):+ actual = model(x)+ expected = reference(ref_x).half()+ self.assert_close(actual, expected, rtol=0.0, atol=0.0)+ actual.flatten()[0].backward()+ expected.flatten()[0].backward()+ self.assert_close(x.grad, ref_x.grad.half())+ for name in ("running_mean", "running_var", "num_batches_tracked"):+ self.assert_close(getattr(model[-1], name), getattr(reference[-1], name), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ @pytest.mark.parametrize("selection", [slice(None), slice(None, -1), slice(1, None), slice(0, 0), slice(None, 3)])+ def test_sequential_slices(self, device, model_cls, selection):+ model = model_cls().to(device)+ block = model.layers if model_cls is SOSNet else model.layer7+ block[-1].running_var.fill_(1e5)+ sliced = block[selection]+ reference = copy.deepcopy(sliced)+ shape = (2, 1, 32, 32) if model_cls is SOSNet else (2, 128, 8, 8)+ x = torch.rand(*shape, device=device, dtype=torch.float16)+ sliced.half()+ for layer in sliced.modules():+ if isinstance(layer, torch.nn.BatchNorm2d):+ assert torch.isfinite(layer.running_var).all()+ if model_cls is SOSNet and selection == slice(None, 3):+ # An intermediate BatchNorm keeps ordinary Sequential half-precision behavior.+ reference = torch.nn.Sequential(*reference).half()+ self.assert_close(sliced(x), reference(x), rtol=0.0, atol=0.0)+ else:+ self.assert_close(sliced(x), reference(x.float()).half())+ assert set(sliced.state_dict()) == set(reference.state_dict())++ @pytest.mark.parametrize("model_cls", [SOSNet, HyNet])+ def test_slicing_does_not_change_source_statistics(self, device, model_cls):+ model = model_cls().to(device).half()+ block = model.layers if model_cls is SOSNet else model.layer7+ before = dict(model.named_buffers())+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float16)+ expected = model(patches)+ for stop in range(1, len(block) + 1):+ block[:stop]+ for name, tensor in model.named_buffers():+ assert tensor is before[name]+ self.assert_close(model(patches), expected, rtol=0.0, atol=0.0)+ # Keeping the original protected norm works even when its position changes.+ block.append(torch.nn.Identity())+ block.insert(0, torch.nn.Identity())+ model.half()+ self.assert_close(model(patches), expected, rtol=0.0, atol=0.0)