🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): make HyNet/SOSNet work in CPU half precision, retire 11 manifest lines (#4225)
Dmytro Mishkine8bc45f8e8c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8165d4771..b5cc97931 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -249,6 +249,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `HyNet` and `SOSNet` now run in half precision, on CPU and on GPU, and no longer return NaN for a+ degenerate patch (closes #4224). Two defects sat on the same line. On CPU both raised+ `NotImplementedError: "avg_pool3d_out_frame" not implemented for 'Half'` (and the `'BFloat16'` spelling):+ their final `LocalResponseNorm` is handed a 4-D `(B, C, 1, 1)` tensor, which routes+ `torch.nn.functional.local_response_norm` through `avg_pool3d`, and that kernel has no CPU+ `float16`/`bfloat16` implementation. Separately, in `float16` on a device where the kernel does exist+ (MPS, CUDA), the descriptors came back all-NaN for any patch the network maps to exactly zero: the `eps`+ that keeps the normalisation's division defined (`SOSNet.forward`'s `eps`, `HyNet`'s `eps_l2_norm`, both+ `1e-10`) is not representable in `float16` and flushes to `0.0`, leaving `0/0`. Every `Conv2d` in `SOSNet`+ has `bias=False` and every `BatchNorm2d` is `affine=False`, so any constant patch reaches the+ normalisation as exactly zero; `HyNet` reaches it only with `is_bias=False`. `bfloat16` keeps `float32`'s+ exponent range, so the guard survives there and only the CPU kernel gap applied to it. Both models now+ take that one normalisation step in `float32` for either half-precision input and cast the result back --+ a wider lift than the `float16`-only one `kornia.feature.siftdesc` gives its own `1e-10` guards, because+ the CPU kernel gap covers both dtypes. `float32` and `float64` take the original expression and are+ bitwise unchanged on CPU, CUDA and MPS. Half-precision output does change, by 0.25-2.25 eps, and where it+ moves most it moves towards the `float64` reference rather than merely away from NaN: `SOSNet` `float16`+ goes from 2.15e-03 to 2.28e-04 of maximum absolute error against a `float64` model carrying the same+ weights, and the configurations that do not improve stay within one eps of where they were.+ Half-precision descriptors are therefore not comparable bit-for-bit across this release. (#4225)* The `Import Surface` CI check accepts deliberate public-name removals recorded in the same change.Edits to `tests/api_surface.json` must correspond to actual export removals and acknowledge only the exactrecorded module/name. Submodule APIs recorded only under an ancestor, and APIs outside the inventory, usediff --git a/conftest.py b/conftest.pyindex e0b48a751..bd3703a2c 100644--- a/conftest.py+++ b/conftest.py@@ -139,6 +139,41 @@ def torch_optimizer(optimizer_backend):return partial(torch.compile, backend=optimizer_backend)+def cudnn_tf32_follows_option(request):+ """Compute convolutions in real float32 on CUDA, so a float32 tolerance means float32.++ The root ``conftest.py``'s ``--tf32`` option drives only ``set_float32_matmul_precision``, which+ does not reach cuDNN: ``torch.backends.cudnn.allow_tf32`` keeps PyTorch's ``True`` default in+ every run. TF32 rounds a convolution's inputs to 10 mantissa bits, and eager and inductor do not+ have to pick the same kernel, so on a deep conv stack the two disagree by ~2e-4 -- twenty times+ ``assert_close``'s float32 ``atol`` -- while the same comparison agrees to 6e-7 once cuDNN is in+ real float32. A compile-vs-eager test that does not take TF32 out of the picture is measuring the+ backend rather than the graph.++ The flag follows ``--tf32`` rather than being forced off, so a ``--tf32`` run still gets TF32 in+ cuDNN as well as in matmul. The repo-wide fix is for ``pytest_sessionstart`` to set+ ``cudnn.allow_tf32`` from the same option; ``tests/color/test_yuv.py`` carries the same local+ workaround for the same reason.++ The alternative -- keeping TF32 on and widening the CUDA float32 bound to ~1e-3, TF32's own+ mantissa -- was tried and dropped: it leaves the assertion a hundred times looser than the signal+ it exists to check, so a genuine compile-vs-eager divergence below 1e-3 would pass. The objection+ to this route is that inductor's on-disk FX graph cache is not keyed on ``allow_tf32``, so a+ context entered after a TF32-on compile in the same process can raise out of+ ``assert_tensor_metadata``. That applies to ``torch.backends.cudnn.flags(...)``, which swaps+ several flags at once; assigning the single attribute, as here and in ``test_yuv.py``, does not+ reproduce it -- ``tests/feature -k "dynamo or compile"`` on CUDA float32 is green with this fixture+ on both a cold and a warm inductor cache.+ """+ previous = torch.backends.cudnn.allow_tf32+ torch.backends.cudnn.allow_tf32 = bool(request.config.getoption("--tf32"))+ try:+ yield+ finally:+ torch.backends.cudnn.allow_tf32 = previous++def _parse_test_option(config, option: str, all_values: dict | set) -> list[str]:"""Parse a test option from CLI, expanding 'all' to full list."""raw_value = config.getoption(option)diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex 90459a6d7..85c8d5adb 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -94,9 +94,12 @@ This page documents which kornia modules support half-precision floating-point d* - ``kornia.feature``- ⚠️ Partial- ⚠️ Partial- - Local feature detectors and descriptors (SIFT, HardNet, DISK, DeDoDe)- work for inference. Feature *matching* uses a manual ``cdist`` fallback- for both half-precision dtypes on CUDA.+ - Local feature detectors and descriptors (SIFT, HardNet, HyNet, SOSNet,+ DISK, DeDoDe) work for inference. ``HyNet`` and ``SOSNet`` take their final+ L2 normalization in float32 for a half-precision input, since+ ``local_response_norm`` has no CPU half kernel for a 4-D tensor and its+ ``1e-10`` guard flushes to zero in float16. Feature *matching* uses a manual+ ``cdist`` fallback for both half-precision dtypes on CUDA.* - ``kornia.metrics``- ⚠️ Partial- ⚠️ Partialdiff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex 654e8cc6d..be147613d 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -293,6 +293,19 @@ class HyNet(nn.Module):x = self.layer5(x)x = self.layer6(x)x = self.layer7(x)- x = self.desc_norm(x + self.eps_l2_norm)+ # Half precision takes this step in float32 and casts back, for two reasons that between them+ # cover both half dtypes. (1) `desc_norm` divides by the descriptor's own L2 norm, and+ # `eps_l2_norm` is what keeps that division defined for a patch the network maps to exactly+ # zero -- which HyNet does with `is_bias=False`. 1e-10 is not representable in float16, where+ # it would flush to 0.0 and leave 0/0; bfloat16 keeps float32's exponent range, so the guard+ # survives there and this half of the argument does not apply to it. (2) `F.local_response_norm`+ # routes a 4-D input through `avg_pool3d`, which has no CPU kernel for *either* half dtype, so+ # the lift is what makes CPU half work at all. Note the lift is therefore wider than the one+ # `siftdesc.py` gives its own 1e-10 guards, which is float16-only for reason (1) alone.+ # float32 and float64 take the original expression unchanged, bit for bit.+ if x.dtype in (torch.float16, torch.bfloat16):+ x = self.desc_norm(x.float() + self.eps_l2_norm).to(x.dtype)+ else:+ x = self.desc_norm(x + self.eps_l2_norm)x = x.view(x.size(0), -1)return xdiff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex d390f9abe..466198ab4 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -100,6 +100,21 @@ class SOSNet(nn.Module):Descriptor tensor with shape :math:`(B, 128)`."""KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])- descr = self.desc_norm(self.layers(input) + eps)+ descr = self.layers(input)+ # Half precision takes this step in float32 and casts back, for two reasons that between them+ # cover both half dtypes. (1) `desc_norm` divides by the descriptor's own L2 norm, and `eps` is+ # what keeps that division defined for a patch the network maps to exactly zero -- every+ # `Conv2d` here has `bias=False` and every `BatchNorm2d` is `affine=False`, so a constant patch+ # does. 1e-10 is not representable in float16, where it would flush to 0.0 and leave 0/0;+ # bfloat16 keeps float32's exponent range, so the guard survives there and this half of the+ # argument does not apply to it. (2) `F.local_response_norm` routes a 4-D input through+ # `avg_pool3d`, which has no CPU kernel for *either* half dtype, so the lift is what makes CPU+ # half work at all. Note the lift is therefore wider than the one `siftdesc.py` gives its own+ # 1e-10 guards, which is float16-only for reason (1) alone.+ # float32 and float64 take the original expression unchanged, bit for bit.+ if descr.dtype in (torch.float16, torch.bfloat16):+ descr = self.desc_norm(descr.float() + eps).to(descr.dtype)+ else:+ descr = self.desc_norm(descr + eps)descr = descr.view(descr.size(0), -1)return descrdiff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 34a3b27a8..f533e3f85 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -116,12 +116,6 @@ call builtins.AssertionError tests/contrib/test_hist_match.py::TestHistMatch::tecall builtins.AssertionError tests/core/test_helpers.py::TestSvdCast::test_smoke[cpu-bfloat16]call builtins.AssertionError tests/enhance/test_jpeg.py::TestDiffJPEG::test_cardinality[cpu-bfloat16]call builtins.AssertionError tests/enhance/test_zca.py::TestZCA::test_dim_args[cpu-bfloat16-1]-call builtins.AssertionError tests/feature/test_aliked.py::TestALIKED::test_descriptor_normalized[cpu-bfloat16]-call builtins.NotImplementedError tests/feature/test_hynet.py::TestHyNet::test_jit[cpu-bfloat16]-call builtins.AssertionError tests/feature/test_responces_local_features.py::TestBlobDoGSingle::test_blobs_batch[cpu-bfloat16]-call builtins.AssertionError tests/feature/test_responces_local_features.py::TestBlobHessian::test_blobs_batch[cpu-bfloat16]-call builtins.AssertionError tests/feature/test_responces_local_features.py::TestCornerGFTT::test_corners_batch[cpu-bfloat16]-call builtins.NotImplementedError tests/feature/test_sosnet.py::TestSOSNet::test_jit[cpu-bfloat16]call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude[cpu-bfloat16]call builtins.RuntimeError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst[cpu-bfloat16]call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst_false[cpu-bfloat16]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 91ea6ac13..7b378a659 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -226,11 +226,6 @@ call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::Tescall builtins.AssertionError tests/color/test_hls.py::TestRgbToHls::test_jit[cpu-float16]call builtins.AssertionError tests/color/test_hls.py::TestRgbToHls::test_module[cpu-float16]call builtins.AssertionError tests/color/test_rgb.py::TestRgb255Normals::test_back_and_forth[cpu-float16]-call builtins.AssertionError tests/feature/test_aliked.py::TestALIKED::test_descriptor_normalized[cpu-float16]-call builtins.NotImplementedError tests/feature/test_hynet.py::TestHyNet::test_jit[cpu-float16]-call builtins.AssertionError tests/feature/test_responces_local_features.py::TestBlobDoGSingle::test_blobs_batch[cpu-float16]-call builtins.AssertionError tests/feature/test_responces_local_features.py::TestCornerGFTT::test_corners_batch[cpu-float16]-call builtins.NotImplementedError tests/feature/test_sosnet.py::TestSOSNet::test_jit[cpu-float16]call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude[cpu-float16]call builtins.RuntimeError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst[cpu-float16]call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst_false[cpu-float16]diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 3e3d399b4..a821327f0 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -169,7 +169,14 @@ class TestALIKED(BaseTester):feat = output[0]if feat.n > 0:norms = feat.descriptors.norm(dim=-1)- assert torch.allclose(norms, torch.ones_like(norms), atol=1e-4)+ # A unit vector stored in `dtype` cannot have a norm closer to 1 than the grid allows, and+ # `norm` itself rounds into that same grid, so the deviation saturates at exactly one eps+ # (measured over 2400+ descriptors on torch 2.9.1 and 2.14.0; taking the norm in float32+ # instead gives 0.55 eps, i.e. the descriptors really are unit to the storage limit).+ # atol=1e-4 is unreachable for float16 (eps 9.8e-4) and bfloat16 (eps 7.8e-3); 2 eps keeps+ # a 2x margin there and leaves float32/float64 on the original bound.+ atol = max(1e-4, 2 * torch.finfo(dtype).eps)+ assert torch.allclose(norms, torch.ones_like(norms), atol=atol)def test_keypoints_in_image(self, dtype, device):"""Keypoints should lie within the image boundaries."""diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.pyindex 8df03f90d..6a7394fea 100644--- a/tests/feature/test_hynet.py+++ b/tests/feature/test_hynet.py@@ -15,11 +15,12 @@# limitations under the License.#+import pytestimport torchfrom kornia.feature import FilterResponseNorm2d, HyNet-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availableclass TestHyNet(BaseTester):@@ -46,6 +47,44 @@ class TestHyNet(BaseTester):hynet = HyNet().to(patches.device, patches.dtype)self.gradcheck(hynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)+ @pytest.mark.parametrize("patch_value", [0.0, 0.5])+ @pytest.mark.parametrize("is_bias", [True, False])+ def test_degenerate_patch_gives_finite_descriptors(self, device, dtype, patch_value, is_bias):+ # `eps_l2_norm` is what keeps `desc_norm`'s division defined for a patch the network maps to+ # exactly zero, and `is_bias=False` is the configuration that gets there: with the TLU bias on,+ # the pre-normalisation tensor never lands exactly on zero. 1e-10 flushes to 0.0 in float16, so+ # the guard used to be inert and every descriptor came back NaN (kornia#4224). bfloat16 keeps+ # float32's exponent range and never had that failure, but on CPU both half dtypes used to+ # raise out of `avg_pool3d` before reaching the division at all, so both are pinned here.+ patches = torch.full((2, 1, 32, 32), patch_value, device=device, dtype=dtype)+ hynet = HyNet(is_bias=is_bias).to(device, dtype).eval()+ descriptors = hynet(patches)+ assert torch.isfinite(descriptors).all(), (+ f"{int((~torch.isfinite(descriptors)).sum())} non-finite descriptor entries"+ )++ def test_dynamo(self, device, dtype, torch_optimizer, cudnn_tf32_follows_option):+ # The normalisation branches on `dtype` to lift half precision into float32. dtype is static+ # metadata, so dynamo resolves that branch at trace time; what this pins is that the compiled+ # result still matches eager on every dtype -- including the lifted half path, which returns+ # NaN if the branch is dropped. `cudnn_tf32_follows_option` is what makes the float32 leg+ # meaningful on CUDA; see its docstring.+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)+ model = HyNet().to(device, dtype).eval()+ op = torch_optimizer(model)+ self.assert_close(op(patches), model(patches))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo_fullgraph(self, device, dtype, cudnn_tf32_follows_option):+ # `export-support.rst` publishes HyNet as capturable with zero graph breaks. The dtype branch+ # reads static metadata and must not become the thing that breaks the graph.+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)+ model = HyNet().to(device, dtype).eval()+ expected = model(patches)+ torch._dynamo.reset()+ compiled = torch.compile(model, fullgraph=True)+ self.assert_close(compiled(patches), expected)+def test_jit(self, device, dtype):B, C, H, W = 2, 1, 32, 32patches = torch.rand(B, C, H, W, device=device, dtype=dtype)diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.pyindex a9512794c..f0e87db82 100644--- a/tests/feature/test_responces_local_features.py+++ b/tests/feature/test_responces_local_features.py@@ -22,6 +22,25 @@ import korniafrom testing.base import BaseTester+def _response_atol(expected: torch.Tensor, dtype: torch.dtype) -> float:+ r"""Absolute bound for a response map compared against hard-coded expected values.++ A response is a difference of quantities of order 1 -- the blurred image and its derivatives --+ so its absolute error is set by one ULP at 1.0 (9.8e-4 float16, 3.9e-3 bfloat16) and *not* by the+ response's own magnitude, which is 0.007-0.28 across these tests. The historical ``atol=1e-4``+ sits below that floor, so in half precision no implementation can meet it; four of these eight+ half-precision nodes were manifest entries for exactly that reason.++ Two ULP is that floor with a 2x margin -- the same bound, and the same reasoning, as+ ``TestALIKED::test_descriptor_normalized``. It is then capped at a twentieth of the largest+ expected value so that the assertion still discriminates: ``harris_response``'s expected map peaks+ at 6.9e-3, *below* bfloat16's own two-ULP floor, and an uncapped bound there would be satisfied by+ an all-zero response. The cap never binds in float32 or float64, and 1e-4 is far above their two+ ULP, so both keep the original bound exactly.+ """+ return min(max(1e-4, 2 * torch.finfo(dtype).eps), expected.abs().max().item() / 20.0)++class TestCornerHarris(BaseTester):def test_shape(self, device):inp = torch.ones(1, 3, 4, 4, device=device)@@ -126,7 +145,7 @@ class TestCornerHarris(BaseTester):/ 10.0)scores = kornia.feature.harris_response(inp, k=0.04)- self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)+ self.assert_close(scores, expected, atol=_response_atol(expected, dtype), rtol=1e-4)def test_gradcheck(self, device):k = 0.04@@ -237,7 +256,7 @@ class TestCornerGFTT(BaseTester):).repeat(2, 1, 1, 1)shi_tomasi = kornia.feature.CornerGFTT().to(device)scores = shi_tomasi(inp)- self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)+ self.assert_close(scores, expected, atol=_response_atol(expected, dtype), rtol=1e-4)def test_gradcheck(self, device):batch_size, channels, height, width = 1, 2, 5, 4@@ -307,7 +326,7 @@ class TestBlobHessian(BaseTester):).repeat(2, 1, 1, 1)shi_tomasi = kornia.feature.BlobHessian().to(device)scores = shi_tomasi(inp)- self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)+ self.assert_close(scores, expected, atol=_response_atol(expected, dtype), rtol=1e-4)def test_gradcheck(self, device):batch_size, channels, height, width = 1, 2, 5, 4@@ -379,7 +398,7 @@ class TestBlobDoGSingle(BaseTester):).expand(2, 2, 7, 7)det = kornia.feature.BlobDoGSingle(1.0, 1.6).to(device)scores = det(inp)- self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)+ self.assert_close(scores, expected, atol=_response_atol(expected, dtype), rtol=1e-4)def test_gradcheck(self, device):batch_size, channels, height, width = 1, 2, 9, 11diff --git a/tests/feature/test_sosnet.py b/tests/feature/test_sosnet.pyindex 4337fa780..a62e75974 100644--- a/tests/feature/test_sosnet.py+++ b/tests/feature/test_sosnet.py@@ -20,7 +20,7 @@ import torchfrom kornia.feature import SOSNet-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availableclass TestSOSNet(BaseTester):@@ -43,9 +43,52 @@ class TestSOSNet(BaseTester):sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype)self.gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4)+ @pytest.mark.parametrize("patch_value", [0.0, 0.5])+ def test_degenerate_patch_gives_finite_descriptors(self, device, dtype, patch_value):+ # `forward`'s `eps` is what keeps `desc_norm`'s division defined for a patch the network maps+ # to exactly zero -- every `Conv2d` here has `bias=False` and every `BatchNorm2d` is+ # `affine=False` with `running_mean == 0`, so a constant patch reaches the normalisation as+ # exactly zero. 1e-10 flushes to 0.0 in float16, so the guard used to be inert and every+ # descriptor came back NaN (kornia#4224). bfloat16 keeps float32's exponent range and never had+ # that failure, but on CPU both half dtypes used to raise out of `avg_pool3d` before reaching+ # the division at all, so both are pinned here.+ patches = torch.full((2, 1, 32, 32), patch_value, device=device, dtype=dtype)+ sosnet = SOSNet().to(device, dtype).eval()+ descriptors = sosnet(patches)+ assert torch.isfinite(descriptors).all(), (+ f"{int((~torch.isfinite(descriptors)).sum())} non-finite descriptor entries"+ )++ def test_dynamo(self, device, dtype, torch_optimizer, cudnn_tf32_follows_option):+ # The normalisation branches on `dtype` to lift half precision into float32. dtype is static+ # metadata, so dynamo resolves that branch at trace time; what this pins is that the compiled+ # result still matches eager on every dtype -- including the lifted half path, which returns+ # NaN if the branch is dropped. `cudnn_tf32_follows_option` is what makes the float32 leg+ # meaningful on CUDA; see its docstring.+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)+ model = SOSNet().to(device, dtype).eval()+ op = torch_optimizer(model)+ self.assert_close(op(patches), model(patches))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo_fullgraph(self, device, dtype, cudnn_tf32_follows_option):+ # `export-support.rst` publishes SOSNet as capturable with zero graph breaks. The dtype branch+ # reads static metadata and must not become the thing that breaks the graph.+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)+ model = SOSNet().to(device, dtype).eval()+ expected = model(patches)+ torch._dynamo.reset()+ compiled = torch.compile(model, fullgraph=True)+ self.assert_close(compiled(patches), expected)+def test_jit(self, device, dtype):B, C, H, W = 2, 1, 32, 32- patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ # `torch.ones` drives a randomly initialised SOSNet to exactly zero (a ReLU collapse), which made+ # this comparison vacuous: both descriptors came out as the constant 1/sqrt(128) and the test+ # scripted a *second*, independently initialised model without noticing. `torch.rand` keeps the+ # network's output non-degenerate; scripting the same instance is what makes the two sides+ # comparable at all. See TestHyNet::test_jit for the pattern.+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)model = SOSNet().to(patches.device, patches.dtype).eval()- model_jit = torch.jit.script(SOSNet().to(patches.device, patches.dtype).eval())+ model_jit = torch.jit.script(model)self.assert_close(model(patches), model_jit(patches))