Skip to content

fix(model): use PyTorch RNG in SparseRandomProjection for reproducibility - #3966

Open
Gelukkig95 wants to merge 2 commits into
open-edge-platform:mainfrom
Gelukkig95:fix/sparse-random-projection-reproducibility
Open

Gelukkig95 wants to merge 2 commits into
open-edge-platform:mainfrom
Gelukkig95:fix/sparse-random-projection-reproducibility

Conversation

@Gelukkig95

Copy link
Copy Markdown

Description

Fixes #3965

SparseRandomProjection._sparse_random_matrix() previously mixed PyTorch RNG (torch.distributions.Binomial) with sklearn.utils.random.sample_without_replacement, causing three issues:

  1. Calling torch.manual_seed() did not make SparseRandomProjection(random_state=None) or KCenterGreedy reproducible, because sample_without_replacement drew from NumPy's global RNG.
  2. Passing an explicit random_state did not seed the PyTorch Binomial draws (nnz_idx, sign data, or the density == 1 branch).
  3. Passing an explicit random_state re-seeded sample_without_replacement with the same integer on every row of the loop, causing rows to select overlapping column subsets.

Changes

  • Replaced sklearn.utils.random.sample_without_replacement in SparseRandomProjection._sparse_random_matrix() with torch.randperm(n_features)[:nnz_idx], unifying all random draws under PyTorch's RNG.
  • When self.random_state is not None, wrapped matrix generation in torch.random.fork_rng(devices=[]) and seeded torch.default_generator.manual_seed(int(self.random_state)) so both dense (density == 1) and sparse branches are reproducible, each row samples independent columns, and the caller's global PyTorch RNG state is preserved.
  • Added unit tests in tests/unit/models/components/dimensionality_reduction/test_random_projection.py.

Verification

  • pytest tests/unit/models/components/dimensionality_reduction/test_random_projection.py tests/unit/models/components/sampling/test_k_center_greedy.py — 30 passed
  • prek run --files src/anomalib/models/components/dimensionality_reduction/random_projection.py tests/unit/models/components/dimensionality_reduction/test_random_projection.py — passed (ruff, ruff format, mypy, bandit)

…lity

Signed-off-by: Gelukkig95 <Gelukkig95@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SparseRandomProjection ignores torch.manual_seed and reuses random_state across rows

1 participant