|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import math |
| 8 | +import unittest |
| 9 | + |
| 10 | +import torch |
| 11 | + |
| 12 | +from executorch.devtools.inspector.numerical_comparator import SNRComparator |
| 13 | + |
| 14 | + |
| 15 | +class TestSNRComparator(unittest.TestCase): |
| 16 | + snr_comparator = SNRComparator() |
| 17 | + |
| 18 | + def test_identical_tensors(self): |
| 19 | + # identical tensors --> error_power == 0 --> SNR is inf |
| 20 | + a = torch.tensor([[10, 4], [3, 4]]) |
| 21 | + b = torch.tensor([[10, 4], [3, 4]]) |
| 22 | + result = self.snr_comparator.compare(a, b) |
| 23 | + self.assertTrue(math.isinf(result) and result > 0) |
| 24 | + |
| 25 | + def test_scalar(self): |
| 26 | + # original_power == 1, error_power == 1 --> SNR = 10 * log10(1/1) = 0 |
| 27 | + a = 1 |
| 28 | + b = 2 |
| 29 | + result = self.snr_comparator.compare(a, b) |
| 30 | + self.assertAlmostEqual(result, 0.0) |
| 31 | + |
| 32 | + def test_with_nans_replaced_with_zero(self): |
| 33 | + a = torch.tensor([float("nan"), 1.0]) |
| 34 | + b = torch.tensor([0.0, 1.0]) |
| 35 | + result = self.snr_comparator.compare(a, b) |
| 36 | + self.assertTrue(math.isinf(result) and result > 0) |
| 37 | + |
| 38 | + def test_shape_mismatch_raises_exception(self): |
| 39 | + a = torch.tensor([1, 2, -1]) |
| 40 | + b = torch.tensor([1, 1, -3, 4]) |
| 41 | + with self.assertRaises(ValueError): |
| 42 | + self.snr_comparator.compare(a, b) |
| 43 | + |
| 44 | + def test_2D_tensors(self): |
| 45 | + # original_power = mean([16, 81, 36, 16]) = 37.25 |
| 46 | + # error = a - b = [3, 7, 3, -1] squared = [9, 49, 9, 1] mean = 68/4 = 17.0 |
| 47 | + # SNR = 10 * log10(37.25/17.0) |
| 48 | + a = torch.tensor([[4, 9], [6, 4]]) |
| 49 | + b = torch.tensor([[1, 2], [3, 5]]) |
| 50 | + expected = 10 * math.log10(37.25 / 17.0) |
| 51 | + result = self.snr_comparator.compare(a, b) |
| 52 | + self.assertAlmostEqual(result, expected) |
| 53 | + |
| 54 | + def test_list_of_tensors(self): |
| 55 | + # original_power = mean(4, 16, 25, 4]) = 12.25 |
| 56 | + # error = a - b = [1, 2, 2, -3] squared = [1, 4, 4, 9] mean = 18/4 = 4.5 |
| 57 | + # SNR = 10 * log10(37.25/17.0) |
| 58 | + a = [torch.tensor([2, 4]), torch.tensor([5, 2])] |
| 59 | + b = [torch.tensor([1, 2]), torch.tensor([3, 5])] |
| 60 | + expected = 10 * math.log10(12.25 / 4.5) |
| 61 | + result = self.snr_comparator.compare(a, b) |
| 62 | + self.assertAlmostEqual(result, expected) |
0 commit comments