|
| 1 | +# Copyright (c) 2026, Alibaba Group; |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +import unittest |
| 13 | + |
| 14 | +import torch |
| 15 | +import torchmetrics |
| 16 | + |
| 17 | +from tzrec.models.sid_model import BaseSidModel |
| 18 | + |
| 19 | + |
| 20 | +class UpdateUniqueSidRatioTest(unittest.TestCase): |
| 21 | + """Unit-test the codebook-coverage metric helper. |
| 22 | +
|
| 23 | + ``_update_unique_sid_ratio`` is pure tensor logic over |
| 24 | + ``self._metric_modules`` (no proto dependency), so it is testable without |
| 25 | + a full ``BaseSidModel`` config — full model coverage waits on the concrete |
| 26 | + subclasses in the follow-up PRs. |
| 27 | + """ |
| 28 | + |
| 29 | + def _bare_model(self) -> BaseSidModel: |
| 30 | + # Bypass __init__ (which needs a pipeline config); only the metric |
| 31 | + # module the helper touches needs to exist. |
| 32 | + model = BaseSidModel.__new__(BaseSidModel) |
| 33 | + model._metric_modules = {"unique_sid_ratio": torchmetrics.MeanMetric()} |
| 34 | + return model |
| 35 | + |
| 36 | + def test_empty_batch_is_noop(self) -> None: |
| 37 | + model = self._bare_model() |
| 38 | + model._update_unique_sid_ratio(torch.empty(0, 3, dtype=torch.long)) |
| 39 | + # The B == 0 guard returns early -> no sample recorded. |
| 40 | + self.assertEqual( |
| 41 | + model._metric_modules["unique_sid_ratio"].weight.item(), 0.0 |
| 42 | + ) |
| 43 | + |
| 44 | + def test_ratio_on_known_duplicates(self) -> None: |
| 45 | + model = self._bare_model() |
| 46 | + # 3 unique rows out of 4 -> ratio 0.75. |
| 47 | + codes = torch.tensor([[1, 2], [1, 2], [3, 4], [5, 6]]) |
| 48 | + model._update_unique_sid_ratio(codes) |
| 49 | + self.assertAlmostEqual( |
| 50 | + model._metric_modules["unique_sid_ratio"].compute().item(), 0.75, places=6 |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + unittest.main() |
0 commit comments