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
7 changes: 4 additions & 3 deletions python/python/lance/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,8 @@ class ShardedBatchSampler(Sampler, _SharedEpoch):
each process will load the entire filtered dataset and discard the rows that are
not assigned to it. The resulting stream is then randomized via a reservoir
sampler. This does not perfectly randomize the stream but it should generate
a stream that is random enough for many use cases.
a stream that is random enough for many use cases. Each randomized filtered
iterator draws from its own generator seeded with the sampler's seed plus epoch.

"""

Expand Down Expand Up @@ -611,7 +612,7 @@ def _sample_filtered(
yield from shard_scan
return

random.seed(self._seed + self._epoch)
rng = random.Random(self._seed + self._epoch)
heap = []
# We want to randomize the incoming sequence. The normal approach
# is to pull the whole thing in memory and run fisher-yates. We
Expand All @@ -627,7 +628,7 @@ def _sample_filtered(
# the default batch size
k = 256
for batch in shard_scan:
priority = random.randint(0, k * 2 - 1)
priority = rng.randint(0, k * 2 - 1)
entry = PrioritizedItem(priority, batch)
if len(heap) < k:
heappush(heap, entry)
Expand Down
21 changes: 21 additions & 0 deletions python/python/tests/test_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,27 @@ def test_sharded_batch_sampler_filter_no_match(tmp_path: Path, randomize):
assert list(sampler(ds, columns=["id"], filter="id > 100")) == []


def test_filtered_sharded_iterators_keep_seeded_order(
tmp_path: Path, preserve_random_state
):
# The filtered shuffle starts yielding after it buffers 256 batches.
dataset = lance.write_dataset(
pa.table({"id": range(280)}), tmp_path, max_rows_per_file=140
)
sampler = ShardedBatchSampler(rank=0, world_size=1, randomize=True, seed=7)
sampler.set_epoch(2)

def ids():
batches = sampler(dataset, columns=["id"], filter="id >= 0", batch_size=1)
return (batch["id"][0].as_py() for batch in batches)

caller_state = random.getstate()
expected = list(ids())
assert sorted(expected) == list(range(280))
assert list(zip(ids(), ids(), strict=True)) == [(row, row) for row in expected]
assert random.getstate() == caller_state


def test_sharded_batch_sampler_filter_keeps_global_rng_without_randomize(
tmp_path: Path, preserve_random_state
):
Expand Down
Loading