diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bb8cd98..5e4d9dbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `align_embeddings()` for mapping pretrained embedding matrices to internal item ID order ([#306](https://github.com/MTSWebServices/RecTools/pull/306)) - `SequenceBatchDataset` — lightweight torch Dataset wrapper for sequence training data ([#306](https://github.com/MTSWebServices/RecTools/pull/306)) - Configurable FFN blocks in `UniSRecNet`: `conv1d` (original paper), `linear_gelu`, `linear_relu` with adjustable expansion factor ([#306](https://github.com/MTSWebServices/RecTools/pull/306)) - +- Optional `avoid_positive_collisions` parameter in `CatalogUniformSampler` to redraw negative samples that collide with positive targets. ## [0.18.0] - 21.02.2026 diff --git a/rectools/models/nn/transformers/negative_sampler.py b/rectools/models/nn/transformers/negative_sampler.py index 27e69e02..5f6bb653 100644 --- a/rectools/models/nn/transformers/negative_sampler.py +++ b/rectools/models/nn/transformers/negative_sampler.py @@ -53,8 +53,20 @@ class CatalogUniformSampler(TransformerNegativeSamplerBase): ---------- n_negatives : int Number of negatives. + avoid_positive_collisions : bool, default False + If True, redraw sampled negatives matching the positive + target at the same position. Redraw is performed once. """ + def __init__( + self, + n_negatives: int, + avoid_positive_collisions: bool = False, + **kwargs: tp.Any, + ) -> None: + super().__init__(n_negatives=n_negatives, **kwargs) + self.avoid_positive_collisions = avoid_positive_collisions + def get_negatives( self, batch_dict: tp.Dict, @@ -65,9 +77,22 @@ def get_negatives( ) -> torch.Tensor: """Return sampled negatives.""" session_len = session_len_limit if session_len_limit is not None else batch_dict["x"].shape[1] + negatives = torch.randint( low=lowest_id, high=highest_id, size=(batch_dict["x"].shape[0], session_len, self.n_negatives), ) # [batch_size, session_max_len, n_negatives] + + if self.avoid_positive_collisions: + targets = batch_dict["y"] + collisions = (negatives == targets.unsqueeze(-1)) & (targets.unsqueeze(-1) != 0) + + if collisions.any(): + negatives[collisions] = torch.randint( + low=lowest_id, + high=highest_id, + size=(int(collisions.sum().item()),), + ) + return negatives diff --git a/tests/models/nn/transformers/test_negative_sampler.py b/tests/models/nn/transformers/test_negative_sampler.py new file mode 100644 index 00000000..f050ed9e --- /dev/null +++ b/tests/models/nn/transformers/test_negative_sampler.py @@ -0,0 +1,82 @@ +import torch + +from rectools.models.nn.transformers.negative_sampler import CatalogUniformSampler + + +def test_catalog_uniform_sampler_default_behavior() -> None: + batch_dict = { + "x": torch.tensor([[1, 2]]), + "y": torch.tensor([[3, 4]]), + } + + torch.manual_seed(42) + expected = torch.randint(1, 10, (1, 2, 2)) + + torch.manual_seed(42) + sampler = CatalogUniformSampler(n_negatives=2) + actual = sampler.get_negatives(batch_dict, lowest_id=1, highest_id=10) + + assert torch.equal(actual, expected) + + +def test_catalog_uniform_sampler_avoids_positive_collisions(monkeypatch) -> None: + batch_dict = { + "x": torch.tensor([[1, 2]]), + "y": torch.tensor([[3, 0]]), + } + + samples = iter([ + torch.tensor([[[3, 5], [6, 7]]]), + torch.tensor([8]), + ]) + + def mock_randint(*args, **kwargs): + return next(samples) + + monkeypatch.setattr(torch, "randint", mock_randint) + + sampler = CatalogUniformSampler( + n_negatives=2, + avoid_positive_collisions=True, + ) + + actual = sampler.get_negatives( + batch_dict, + lowest_id=1, + highest_id=10, + ) + + expected = torch.tensor([[[8, 5], [6, 7]]]) + + assert torch.equal(actual, expected) + +def test_catalog_uniform_sampler_redraws_only_once(monkeypatch) -> None: + batch_dict = { + "x": torch.tensor([[1]]), + "y": torch.tensor([[3]]), + } + + samples = iter([ + torch.tensor([[[3, 5]]]), + torch.tensor([3]), + ]) + + def mock_randint(*args, **kwargs): + return next(samples) + + monkeypatch.setattr(torch, "randint", mock_randint) + + sampler = CatalogUniformSampler( + n_negatives=2, + avoid_positive_collisions=True, + ) + + actual = sampler.get_negatives( + batch_dict, + lowest_id=1, + highest_id=10, + ) + + expected = torch.tensor([[[3, 5]]]) + + assert torch.equal(actual, expected) \ No newline at end of file