Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): stabilize half-precision mutual information (#5815)

peng xiang656946d5479e
diff --git a/README.md b/README.md
index 042528df4..d28946b69 100644
--- a/README.md
+++ b/README.md
@@ -109,7 +109,7 @@ covers CUDA or MPS half precision.
| `kornia.geometry.ransac` | ⚠️ | ⚠️ | 4 / 4 | The essential and fundamental models raise through the epipolar solvers |
| `kornia.geometry` (other) | ⚠️ | ⚠️ | 8 / 17 | Accuracy in boxes, depth and line utilities; bfloat16 `NamedPose` construction raises |
| `kornia.image` | ⚠️ | ⚠️ | 4 / 4 | `draw_convex_polygon` fill accuracy |
-| `kornia.losses` | ⚠️ | ⚠️ | 3 / 4 | Dice averaging overflows to inf/NaN in float16; mutual information range check; bfloat16 Dice weighting and total variation |
+| `kornia.losses` | ⚠️ | ⚠️ | 2 / 2 | Dice averaging overflows to inf/NaN in float16; bfloat16 total variation; mutual information passes |
| `kornia.feature` | βœ… | βœ… | 0 / 0 | Matching uses a manual `cdist` fallback for half dtypes; LightGlue's float16 tests are skipped, so that path is unmeasured |
| `kornia.metrics` | βœ… | ⚠️ | 0 / 1 | bfloat16: `ssim3d` accuracy |
| `kornia.models` | βœ… | ⚠️ | 0 / 1 | bfloat16 RT-DETR RepVGG fusion accuracy |
diff --git a/changelog.d/5815.fixed.md b/changelog.d/5815.fixed.md
new file mode 100644
index 000000000..bb56c7564
--- /dev/null
+++ b/changelog.d/5815.fixed.md
@@ -0,0 +1 @@
+Mutual-information and normalized mutual-information losses now compute half-precision normalization, kernel weights, joint histograms and entropies in float32 and return the input dtype. float16 losses and gradients, NaN from about 184 Γ— 184 pixels with the default kernel, are now finite, and both half dtypes lose the empty-bin bias on small images (12 Γ— 20 seeded pair: float32 βˆ’2.662; float16 βˆ’2.547 β†’ βˆ’2.662; bfloat16 βˆ’2.063 β†’ βˆ’2.656). The histogram contraction now ignores autocast, so a float32 input inside an autocast region is computed and returned in float32; before, the contraction ran in the autocast dtype, which gave NaN under float16 autocast on large images and a bfloat16 result under CPU bfloat16 autocast. `entropies()` of a half-precision module returns float32. Cached reference modules keep the original dtype's constant-signal threshold and the same state dictionary keys.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 760547dc4..41eb73f9a 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -129,9 +129,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.losses``
- ⚠️ Partial
- ⚠️ Partial
- - 3 / 3
- - Dice averaging overflows to inf/NaN in float16; the mutual-information range check fails in both
- dtypes; bfloat16 total variation misses accuracy. Hausdorff and the photometric losses pass.
+ - 2 / 2
+ - Dice averaging overflows to inf/NaN in float16; bfloat16 total variation misses accuracy.
+ Mutual information, Hausdorff and the photometric losses pass.
* - ``kornia.feature``
- βœ… Yes
- βœ… Yes
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index 41ecb5632..e6e114b9c 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -217,11 +217,16 @@ class EntropyBasedLossBase(torch.nn.Module):
self._ref_mask_is_full = _mask_is_full(mask)
mask = self.fix_mask(mask, reference_signal)
eps = torch.finfo(reference_signal.dtype).eps
+ # The normalized cache may use float32; retain the caller's dtype for the range threshold and result.
+ # This empty, non-persistent buffer follows Module.to without adding a state_dict key.
+ self.register_buffer("_reference_dtype", reference_signal.new_empty(0), persistent=False)
self.initial_shape = reference_signal.shape
signal = reference_signal[..., mask]
# Without a mask the gather keeps every sample: checking its size would guard on a data-dependent size
# and break ``fullgraph`` capture.
KORNIA_CHECK(self._ref_mask_is_full or signal.shape[-1] > 0, "mask must select at least one sample.")
+ if signal.dtype in (torch.float16, torch.bfloat16):
+ signal = signal.float()
self.register_buffer("signal", _normalize_signal(signal, num_bins, eps))
# Keep the mask consistent with the cached reference if the caller edits its tensor.
self.register_buffer("mask", mask.clone())
@@ -233,8 +238,8 @@ class EntropyBasedLossBase(torch.nn.Module):
@property
def eps(self) -> float:
- """Machine epsilon of the cached reference signal, so that it follows ``Module.to(dtype)``."""
- return torch.finfo(self.signal.dtype).eps
+ """Machine epsilon of the reference dtype, so that it follows ``Module.to(dtype)``."""
+ return torch.finfo(self._reference_dtype.dtype).eps
@staticmethod
def fix_mask(mask: torch.Tensor, masked_guy: torch.Tensor) -> torch.Tensor:
@@ -306,6 +311,8 @@ class EntropyBasedLossBase(torch.nn.Module):
f"The two signals have incompatible shapes: {other_signal.shape} and {self.initial_shape}."
)
_validate_mask(other_mask, other_signal.shape[-1:])
+ if other_signal.dtype in (torch.float16, torch.bfloat16):
+ other_signal = other_signal.float()
if self._ref_mask_is_full and _mask_is_full(other_mask):
# No roi on either side: skip the boolean-mask gathers, whose output sizes depend on the
# mask values and therefore cannot be captured by ``torch.export``/ONNX.
@@ -322,13 +329,20 @@ class EntropyBasedLossBase(torch.nn.Module):
other_signal = self.trace_in_ref_mask(other_signal, other_mask)
other_signal = other_signal[..., common_mask]
+ # Evaluate kernels and accumulate counts in float32 for half inputs. A half-precision histogram can
+ # overflow before its probabilities are formed, even if every kernel weight is representable.
+ if ref_signal.dtype in (torch.float16, torch.bfloat16):
+ ref_signal = ref_signal.float()
+ other_signal = other_signal.float()
diff_1 = self.bin_centers.unsqueeze(-1) - ref_signal.unsqueeze(-2)
diff_2 = self.bin_centers.unsqueeze(-1) - other_signal.unsqueeze(-2)
vals_1 = self.kernel_function(diff_1)
vals_2 = self.kernel_function(diff_2)
- return torch.einsum("...in,...jn->...ij", vals_1, vals_2)
+ # Autocast would undo the promotion at this matrix multiplication.
+ with torch.autocast(device_type=other_signal.device.type, enabled=False):
+ return torch.einsum("...in,...jn->...ij", vals_1, vals_2)
def entropies(
self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None
@@ -349,14 +363,15 @@ class EntropyBasedLossBase(torch.nn.Module):
- Marginal entropy of the reference signal
- Joint entropy
- All tensors have the same batch dimensions as the input signals.
+ All tensors have the same batch dimensions as the input signals. Half-precision inputs produce
+ float32 entropies; the loss subclasses cast their final result back to the reference dtype.
Note:
Subclasses should implement specific loss functions based on these entropy
measures (e.g., mutual information).
"""
joint_histogram = self._compute_joint_histogram(other_signal, self.eps, other_mask)
- return _joint_histogram_to_entropies(joint_histogram, eps=self.eps)
+ return _joint_histogram_to_entropies(joint_histogram, eps=torch.finfo(joint_histogram.dtype).eps)
class MILossFromRef(EntropyBasedLossBase):
@@ -375,6 +390,9 @@ class MILossFromRef(EntropyBasedLossBase):
tensor or to the mask tensor are not seen. The cache is not detached: a reference that requires grad
receives a gradient from the first backward pass, and a second backward pass through the same module
raises.
+ Half-precision references are normalised and cached in float32. The final loss and constant-signal
+ threshold follow the original reference dtype, including after ``.to(dtype)``; converting the cache
+ itself to a lower precision can round its stored bin positions.
"""
def forward(self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None) -> torch.Tensor:
@@ -396,7 +414,7 @@ class MILossFromRef(EntropyBasedLossBase):
H_x, H_y, H_xy = self.entropies(other_signal, other_mask)
mi = H_x + H_y - H_xy
- return -mi
+ return (-mi).to(self._reference_dtype.dtype)
class NMILossFromRef(EntropyBasedLossBase):
@@ -430,7 +448,7 @@ class NMILossFromRef(EntropyBasedLossBase):
H_x, H_y, H_xy = self.entropies(other_signal, other_mask)
nmi = (H_x + H_y) / H_xy
- return -nmi
+ return (-nmi).to(self._reference_dtype.dtype)
class MILossFromRef2D(MILossFromRef):
@@ -819,11 +837,10 @@ def mutual_information_loss(
positions inside both masks, while each signal is normalised over its own mask: a value inside one mask
only is not counted, but it changes the loss when it is that signal's minimum or maximum. Values outside
both masks have no effect. Masks of another shape, or with no position in common, raise an error.
- - Known defect: in float16 and bfloat16 the empty bins are floored at ``torch.finfo(dtype).eps`` counts
- before the histogram is normalised: both dtypes bias the loss of small images, and float16 returns NaN for
- large ones, from about ``2**15 / window_radius**2`` pixels with the default ``MIKernel.xu``, from a
- quarter of that with ``MIKernel.rectangular`` and from about ``2**16`` pixels, whatever the radius, with
- ``MIKernel.truncated_gaussian`` (`#4153 <https://github.com/kornia/kornia/issues/4153>`_).
+ - For float16 and bfloat16 inputs, min-max normalisation, kernel evaluation, histogram accumulation and
+ entropy arithmetic use float32, including under autocast, and the final loss is cast back to the input
+ dtype. The empty-bin floor uses the histogram's computation dtype rather than the input dtype.
+ The constant-signal threshold remains ``torch.finfo(input dtype).eps``.
Args:
input (torch.Tensor): Batch of flat tensors shape (B,N) where B
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 1d132f7dd..c30cf3ce1 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -415,7 +415,6 @@ call builtins.AssertionError tests/integration/test_conversions.py::TestQuaterni
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-0]
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-1]
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-2]
-call builtins.AssertionError tests/losses/test_mutual_information.py::TestMutualInformationLoss::test_value_ranges[cpu-bfloat16]
call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_3d[cpu-bfloat16-pred0-expected0]
call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_4d[cpu-bfloat16-pred0-expected0]
call builtins.AssertionError tests/models/test_rt_detr.py::test_regvgg_optimize_for_deployment[cpu-bfloat16]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 112fd99ab..b4376ec03 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -301,4 +301,3 @@ call builtins.AssertionError tests/integration/test_conversions.py::TestQuaterni
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-float16-2]
call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_averaging_macro[cpu-float16]
call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_averaging_micro[cpu-float16]
-call builtins.AssertionError tests/losses/test_mutual_information.py::TestMutualInformationLoss::test_value_ranges[cpu-float16]
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index 3837aa0a5..c36d76488 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -63,9 +63,13 @@ class TestMutualInformationLoss(BaseTester):
img_3 = self.sampling_function(n_samples, device, dtype)
for radius in [1 / 2, 1, 2, 3]:
- # relative MI, expect 1
+ # Half inputs round the affine transform, so they are not exactly related by an affine map.
+ # Allow one representable step rather than float32's default allclose.
+ correlated_tolerance = torch.finfo(dtype).eps if dtype in (torch.float16, torch.bfloat16) else 1e-5
assert torch.allclose(
- self.relative_mi(img_1, img_2, window_radius=radius), torch.ones(1, dtype=dtype, device=device)
+ self.relative_mi(img_1, img_2, window_radius=radius),
+ torch.ones(1, dtype=dtype, device=device),
+ rtol=correlated_tolerance,
), "Wrong MI behaviour, correlated case."
# relative MI, expect 0
# NOTE: mutual_information_loss is a finite-sample, histogram-based estimator applied to random data.
@@ -198,12 +202,12 @@ class TestMutualInformationLoss(BaseTester):
joint_histogram = module._compute_joint_histogram(pred, module.eps)
self.assert_close(
- joint_histogram.sum((-2, -1)), torch.full((2, 3), 20.0, device=device, dtype=dtype), low_tolerance=True
+ joint_histogram.sum((-2, -1)),
+ torch.full((2, 3), 20.0, device=device, dtype=joint_histogram.dtype),
+ low_tolerance=True,
)
def test_binary_mask_mutual_information_is_its_entropy(self, device, dtype):
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("the entropies need full precision to match the hard histogram")
generator = torch.Generator().manual_seed(0)
# the float64 oracle is computed on the CPU: MPS has no float64
mask = (torch.rand(12, 20, generator=generator) > 0.5).double()
@@ -218,8 +222,6 @@ class TestMutualInformationLoss(BaseTester):
)
def test_integer_levels_match_hard_histogram(self, device, dtype):
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip("the entropies need full precision to match the hard histogram")
levels = 4
# the float64 oracle is computed on the CPU: MPS has no float64
pred = torch.tensor([[0, 1, 2, 3], [3, 2, 1, 0], [0, 0, 3, 3]])
@@ -597,12 +599,6 @@ class TestMutualInformationEagerBackendTraces(BaseTester):
self.assert_close(compiled(signal, target), loss_fn(signal, target))
-_HALF_FLOOR_SKIP = (
- "MI in half precision is biased by the empty-bin floor finfo(dtype).eps, applied in count units before the "
- "histogram is normalised (#4153)"
-)
-
-
@cache
def _supports_bool_index_backward(device_type: str, dtype: torch.dtype) -> bool:
"""Whether boolean-mask indexing has a backward kernel here (torch 2.5.1 has none for MPS half).
@@ -649,8 +645,8 @@ class TestConventionsMutualInformation(BaseTester):
x, y = a.flatten(-2), c.flatten(-2)
# the module built on the target returns the marginal entropies of the joint histogram and its joint entropy
h_1, h_2, h_12 = MILossFromRef(y).entropies(x)
- self.assert_close(mutual_information_loss(x, y), -(h_1 + h_2 - h_12))
- self.assert_close(normalized_mutual_information_loss(x, y), -(h_1 + h_2) / h_12)
+ self.assert_close(mutual_information_loss(x, y), (-(h_1 + h_2 - h_12)).to(dtype))
+ self.assert_close(normalized_mutual_information_loss(x, y), (-(h_1 + h_2) / h_12).to(dtype))
# minimising the loss maximises the dependence: identical < dependent < independent, per sample
mi = [mutual_information_loss_2d(a, t) for t in (a, c, b)]
nmi = [normalized_mutual_information_loss_2d(a, t) for t in (a, c, b)]
@@ -714,7 +710,6 @@ class TestConventionsMutualInformation(BaseTester):
# the threshold is absolute: a * eps / 4 spans about eps / 2, although its relative range is about 1
tiny = a * (eps / 4)
for x, y in ((a, constant), (constant, c), (tiny, c)):
- # num_bins=16 keeps the empty-bin floor small in half precision; the rule does not depend on it
mi = mutual_information_loss_2d(x, y, num_bins=16)
nmi = normalized_mutual_information_loss_2d(x, y, num_bins=16)
assert (mi.abs() < 0.05).all()
@@ -915,8 +910,6 @@ class TestConventionsMutualInformation(BaseTester):
assert (grad.abs().flatten(1).sum(1) > 0).all()
def test_convention_mi_losses_num_bins_and_window_radius_set_the_resolution(self, device, dtype):
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip(_HALF_FLOOR_SKIP)
a, c, _ = self._images(device, dtype)
# On this fixture finer bins raise MI and a wider kernel lowers it; these are not general monotonic rules.
mi_aa = [mutual_information_loss_2d(a, a, num_bins=n) for n in (4, 16, 64)]
@@ -942,8 +935,6 @@ class TestConventionsMutualInformation(BaseTester):
def test_convention_mi_losses_match_hard_histograms_on_integer_levels_5546(self, device, dtype):
"""Integer levels 0 .. K on the bin centres (``num_bins=K + 1``) give the hard-histogram MI and NMI (#5546)."""
- if dtype in (torch.float16, torch.bfloat16):
- pytest.skip(_HALF_FLOOR_SKIP + "; float16 entropies also miss the reference literals' tolerance")
# levels 0 .. 8 with both extremes present normalise onto the centres 0 .. 8 of num_bins=9, where the
# default kernel puts every pixel, the maximum included, in its own bin. scikit-learn 1.9.0 /
# scikit-image 0.26.0 (numpy 2.0.0) on the same arrays:
@@ -962,8 +953,8 @@ class TestConventionsMutualInformation(BaseTester):
def test_convention_mi_from_ref_follows_to_dtype_5547(self, device, dtype):
"""A ``FromRef`` module moved with ``.to(dtype)`` computes like one built in that dtype (#5547)."""
- # each move crosses a large gap in eps (MPS has no float64), so a module that kept its construction eps,
- # the empty-bin floor, would compute a different loss (into float16: NaN)
+ # Each move crosses a gap in computation precision (MPS has no float64), so the entropy floor must
+ # follow the histogram dtype instead of keeping the dtype used at construction.
if dtype in (torch.float16, torch.bfloat16):
moved_dtype = torch.float32
elif dtype == torch.float32 and device.type != "mps":
@@ -973,7 +964,6 @@ class TestConventionsMutualInformation(BaseTester):
# integer levels 0 .. 4 normalise to multiples of (num_bins - 1) / 4 exactly in every dtype, so the cached
# reference converts exactly and any difference comes from the module's own state
reference = self._levels(device)[0] % 5
- # eps acts here as the empty-bin floor (#4153); re-derive the fixture if the floor changes
moved = MILossFromRef2D(reference.to(dtype)).to(moved_dtype)
native = MILossFromRef2D(reference.to(moved_dtype))
assert torch.equal(moved.signal, native.signal)
@@ -993,18 +983,57 @@ class TestConventionsMutualInformation(BaseTester):
target_mask[0, 0] = True
self.assert_close(module(a), expected, rtol=0, atol=0)
- def test_wart_mi_losses_float16_nan_on_a_large_image_4153(self, device, dtype):
- """The empty-bin floor of ``finfo(dtype).eps`` counts makes float16 NaN on large images (#4153)."""
- if dtype != torch.float16:
- pytest.skip("float16 only: the floor eps / mass rounds to 0 once the mass passes 2**15")
+ @pytest.mark.parametrize("shape", [(12, 20), (184, 184)])
+ @pytest.mark.parametrize("kernel", list(MIKernel))
+ @pytest.mark.parametrize("loss_fn", [mutual_information_loss_2d, normalized_mutual_information_loss_2d])
+ @pytest.mark.parametrize("masked", [False, True])
+ def test_convention_mi_losses_half_precision_match_float32_4153(
+ self, device, dtype, shape, kernel, loss_fn, masked
+ ):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision regression")
g = torch.Generator().manual_seed(7)
- u = torch.rand(184, 184, generator=g, dtype=torch.float64)
- v = u**2 + 0.05 * torch.rand(184, 184, generator=g, dtype=torch.float64)
+ u = torch.rand(shape, generator=g)
+ v = u**2 + 0.05 * torch.rand(shape, generator=g)
x, y = u.to(device, dtype), v.to(device, dtype)
- assert torch.isnan(mutual_information_loss_2d(x, y)).all()
- # control: a smaller image in float16 and the same image in float32 are finite
- assert torch.isfinite(mutual_information_loss_2d(x[:120, :120], y[:120, :120])).all()
- assert torch.isfinite(mutual_information_loss_2d(x.float(), y.float())).all()
- # the rectangular kernel counts each sample in about two bins per signal, four times xu's histogram mass
- rect = mutual_information_loss_2d(x[:100, :100], y[:100, :100], kernel_function=MIKernel.rectangular)
- assert torch.isnan(rect).all()
+ mask = (torch.arange(x.numel(), device=device).reshape(shape) % 3 != 1) if masked else None
+ # Compare the same representable inputs: quantization of the supplied image is unavoidable.
+ expected = loss_fn(x.float(), y.float(), mask, mask, kernel_function=kernel).to(dtype)
+ actual = loss_fn(x, y, mask, mask, kernel_function=kernel)
+ assert actual.dtype == dtype
+ assert actual.device == device
+ assert actual.isfinite().all()
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ if kernel is not MIKernel.rectangular:
+ if not _supports_bool_index_backward(device.type, dtype):
+ pytest.skip("no boolean-index backward kernel for this device and dtype")
+ x, y = x.requires_grad_(), y.requires_grad_()
+ gradients = torch.autograd.grad(loss_fn(x, y, mask, mask, kernel_function=kernel), (x, y))
+ ref_x, ref_y = x.detach().float().requires_grad_(), y.detach().float().requires_grad_()
+ expected_gradients = torch.autograd.grad(
+ loss_fn(ref_x, ref_y, mask, mask, kernel_function=kernel), (ref_x, ref_y)
+ )
+ for grad, expected_grad in zip(gradients, expected_gradients):
+ assert grad.isfinite().all()
+ assert grad.abs().sum() > 0
+ self.assert_close(grad, expected_grad.to(dtype))
+ if masked:
+ self.assert_close(grad[~mask], torch.zeros_like(grad[~mask]), rtol=0, atol=0)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize(
+ "loss_fn,expected", [(mutual_information_loss, -math.log(2)), (normalized_mutual_information_loss, -2.0)]
+ )
+ def test_convention_mi_losses_count_half_histograms_in_float32_under_autocast_4153(self, dtype, loss_fn, expected):
+ # Two equally likely binary levels have MI=ln(2) and NMI=2. Their count sum (70000) overflows float16;
+ # CPU autocast would also demote a float32 einsum back to bfloat16 and round the two marginal counts.
+ signal = (torch.arange(70000) % 2).to(dtype)
+ kwargs = {"num_bins": 2, "kernel_function": MIKernel.rectangular, "window_radius": 0.5}
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ actual = loss_fn(signal, signal, **kwargs)
+ histogram = MILossFromRef(signal, **kwargs)._compute_joint_histogram(signal, torch.finfo(dtype).eps)
+ assert actual.dtype == dtype
+ assert histogram.dtype == torch.float32
+ self.assert_close(histogram.sum(), torch.tensor(70000.0), rtol=0, atol=0)
+ self.assert_close(actual, signal.new_tensor(expected))