Skip to content

[fix] Fix different batches per epoch in NoDuplicatesBatchSampler #3073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 20, 2024
Merged
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
8 changes: 6 additions & 2 deletions sentence_transformers/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,10 @@ def __iter__(self) -> Iterator[list[int]]:
if self.generator and self.seed:
self.generator.manual_seed(self.seed + self.epoch)

remaining_indices = set(torch.randperm(len(self.dataset), generator=self.generator).tolist())
# We create a dictionary to None because we need a data structure that:
# 1. Allows for cheap removal of elements
# 2. Preserves the order of elements, i.e. remains random
remaining_indices = dict.fromkeys(torch.randperm(len(self.dataset), generator=self.generator).tolist())
while remaining_indices:
batch_values = set()
batch_indices = []
Expand All @@ -209,7 +212,8 @@ def __iter__(self) -> Iterator[list[int]]:
if not self.drop_last:
yield batch_indices

remaining_indices -= set(batch_indices)
for index in batch_indices:
del remaining_indices[index]

def __len__(self) -> int:
if self.drop_last:
Expand Down