Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 25 additions & 0 deletions rectools/models/nn/transformers/negative_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
82 changes: 82 additions & 0 deletions tests/models/nn/transformers/test_negative_sampler.py
Original file line number Diff line number Diff line change
@@ -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)