-
Notifications
You must be signed in to change notification settings - Fork 6
chore: sampler serialization tests #250
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
Open
selmanozleyen
wants to merge
5
commits into
scverse:main
Choose a base branch
from
selmanozleyen:chore/sampler-serialization-tests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+162
−2
Open
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d2405fd
init without precommit
selmanozleyen b39bb6c
Merge branch 'main' into chore/sampler-serialization-tests
selmanozleyen 64846b2
add deepcopy test and remove sequentialsampler test
selmanozleyen 4d8b3b6
remove unnecessary extra advance hence the helper func
selmanozleyen d569be8
implement eq, deepcopy, and not copy. Also add tests
selmanozleyen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,17 +2,20 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| import copy | ||
| import math | ||
| import pickle | ||
| import sys | ||
| from functools import partial | ||
| from typing import TYPE_CHECKING | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import numpy as np | ||
| import pandas as pd | ||
| import pytest | ||
|
|
||
| from annbatch.abc import Sampler | ||
| from annbatch.samplers import DistributedSampler, RandomSampler, SequentialSampler | ||
| from annbatch.samplers import ClassSampler, DistributedSampler, RandomSampler, SequentialSampler | ||
| from annbatch.samplers._utils import WorkerInfo | ||
|
|
||
| if TYPE_CHECKING: | ||
|
|
@@ -879,3 +882,74 @@ def test_wraps_sequential_sampler(self, make_distributed_sampler: Callable[..., | |
| for j in range(i + 1, world_size): | ||
| assert set(all_indices[i]).isdisjoint(set(all_indices[j])) | ||
| assert set().union(*all_indices) == set(range(n_obs)) | ||
|
|
||
|
|
||
| # ============================================================================= | ||
| # Serialization / reproducibility (all implemented stochastic samplers) | ||
| # ============================================================================= | ||
|
|
||
|
|
||
| def _make_sampler(kind: str, seed: int, n_obs: int) -> Sampler: | ||
| """Build the sampler identified by ``kind``, seeded with ``seed``, sized for ``n_obs`` obs.""" | ||
| match kind: | ||
| case "random": | ||
| return RandomSampler(chunk_size=10, preload_nchunks=2, batch_size=5, rng=np.random.default_rng(seed)) | ||
| case "class": | ||
| # n_obs obs, 5 classes, each a contiguous run of n_obs // 5 (>= chunk_size) | ||
| classes = pd.Categorical(np.repeat(np.arange(5), n_obs // 5)) | ||
| return ClassSampler( | ||
| chunk_size=10, | ||
| preload_nchunks=2, | ||
| batch_size=5, | ||
| classes=classes, | ||
| num_samples=50, | ||
| rng=np.random.default_rng(seed), | ||
| ) | ||
| case "distributed": | ||
| inner = RandomSampler(chunk_size=10, preload_nchunks=2, batch_size=5, rng=np.random.default_rng(seed)) | ||
| # dist_info is only called at construction (rank 0 of 1) and is not stored, | ||
| # so the resulting sampler stays picklable/copyable. | ||
| return DistributedSampler(inner, dist_info=lambda: (0, 1)) | ||
| case _: | ||
| raise ValueError(f"unknown sampler kind {kind!r}") | ||
|
|
||
|
|
||
| # A round-trip duplicates a sampler into an *independent* object with the same state. | ||
| # ``copy.deepcopy`` -- not shallow ``copy.copy`` -- is the copy analog of pickle: a shallow | ||
| # copy would share the ``rng`` object with the original, breaking the independence these | ||
| # assertions rely on. | ||
| _ROUND_TRIPS = { | ||
| "pickle": lambda sampler: pickle.loads(pickle.dumps(sampler)), | ||
| "deepcopy": copy.deepcopy, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("round_trip", _ROUND_TRIPS.values(), ids=_ROUND_TRIPS.keys()) | ||
| @pytest.mark.parametrize("kind", ["random", "class", "distributed"]) | ||
| def test_sampler_is_serializable_and_reproducible(kind: str, round_trip: Callable[[Sampler], Sampler]): | ||
| """Every sampler survives a pickle/deepcopy round-trip with its random *state* (not just the seed) preserved.""" | ||
| n_obs = 100 | ||
|
|
||
| def advance_round_trip_indices(seed: int) -> list[int]: | ||
| sampler = _make_sampler(kind, seed, n_obs) | ||
| collect_indices(sampler, n_obs) # advance the rng one pass | ||
| restored = round_trip(sampler) | ||
| indices, _, _ = collect_indices(restored, n_obs) | ||
| return indices | ||
|
|
||
| sampler = _make_sampler(kind, seed=0, n_obs=n_obs) | ||
| fresh_indices, _, _ = collect_indices(_make_sampler(kind, seed=0, n_obs=n_obs), n_obs) | ||
|
|
||
| # advance the rng by one full pass, then snapshot via the round-trip | ||
| collect_indices(sampler, n_obs) | ||
| restored = round_trip(sampler) | ||
| assert isinstance(restored, type(sampler)) | ||
|
|
||
| restored_indices, _, _ = collect_indices(restored, n_obs) | ||
| original_indices, _, _ = collect_indices(sampler, n_obs) | ||
| assert restored_indices, "sampler produced no indices" | ||
|
|
||
| assert restored_indices == original_indices | ||
| assert restored_indices != fresh_indices | ||
| assert restored_indices == advance_round_trip_indices(seed=0) | ||
| assert restored_indices != advance_round_trip_indices(seed=1) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is this testing? |
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do we need to advance the rng first here and below?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because this also tests randomness. For example maybe we override the rng to always to np.default(0). The tests would still pass otherwise.
I mean we already test randomness somewhere else but I wrote it in the very small chance that the seed I set and whatever seed could be set in the case of such a faulty override would be the same
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't follow - if you provide a seed explicitly, why does it matter how many times you advance state before/after making a copy?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah you are right sorry.