Repository navigation
Replace NumPy global RNG use in tests with local seeded RNGs - #8084
Conversation
📝 WalkthroughWalkthroughReplaces non-deterministic/global NumPy RNG usage in many tests with local, fixed-seed Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (5)
tests/skimage/transform/test_geometric.py (1)
1015-1015: Rename the unused loop indices to_.
iis never read in either loop, so Ruff B007 will keep flagging these blocks.Also applies to: 1077-1077
tests/skimage/feature/test_corner.py (1)
642-645: Rename the unused loop counter to_.The loop variable on line 644 is declared but never referenced in the loop body. Using
_makes the intent explicit and prevents linter warnings.Suggested diff
- for i in range(20): + for _ in range(20): n = rng.randint(1, 21) results = peak_local_max( img_corners, min_distance=10, threshold_rel=0, num_peaks=n )tests/skimage/registration/test_ilk.py (2)
119-124: Drop the unused tuple assignments insidepytest.raises.These calls are only here for the exception side effect, and
u, v =is what Ruff is warning about in this touched code.♻️ Suggested cleanup
def test_incompatible_shapes(): rng = np.random.RandomState(811850096) I0 = rng.randn(256, 256) I1 = rng.randn(255, 256) with pytest.raises(ValueError): - u, v = optical_flow_ilk(I0, I1) + optical_flow_ilk(I0, I1) def test_wrong_dtype(): rng = np.random.RandomState(87830699) img = rng.randn(256, 256) with pytest.raises(ValueError): - u, v = optical_flow_ilk(img, img, dtype='int') + optical_flow_ilk(img, img, dtype='int')Also applies to: 127-131
67-69: UseRandomStatehere for consistency with other touched tests in this file.All other modified tests in
test_ilk.pyusenp.random.RandomState(lines 43, 81, 90, 100, 120, 128), but this test usesnp.random.default_rng. Since the usage is straightforward (onlyrng.normal()), switching toRandomStatewould align with the PR's apparent standardization on that RNG API for long-term stable test data. IfGeneratoris necessary here, document that rationale.tests/skimage/registration/test_tvl1.py (1)
107-112: Drop the unused tuple assignments insidepytest.raises.The assignments are not used, and the exception assertion works the same without them.
♻️ Suggested cleanup
def test_incompatible_shapes(): rng = np.random.RandomState(4152361355) I0 = rng.randn(256, 256) I1 = rng.randn(128, 256) with pytest.raises(ValueError): - u, v = optical_flow_tvl1(I0, I1) + optical_flow_tvl1(I0, I1) def test_wrong_dtype(): rng = np.random.RandomState(740440569) img = rng.randn(256, 256) with pytest.raises(ValueError): - u, v = optical_flow_tvl1(img, img, dtype=np.int64) + optical_flow_tvl1(img, img, dtype=np.int64)Also applies to: 115-119
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2b331534-9889-4a32-8a06-5e8dd39b400d
📒 Files selected for processing (61)
CONTRIBUTING.rsttests/skimage/_shared/test_coord.pytests/skimage/color/test_colorconv.pytests/skimage/color/test_colorlabel.pytests/skimage/exposure/test_exposure.pytests/skimage/feature/test_basic_features.pytests/skimage/feature/test_brief.pytests/skimage/feature/test_canny.pytests/skimage/feature/test_censure.pytests/skimage/feature/test_corner.pytests/skimage/feature/test_fisher_vector.pytests/skimage/feature/test_peak.pytests/skimage/feature/test_template.pytests/skimage/feature/test_texture.pytests/skimage/feature/test_util.pytests/skimage/filters/rank/test_rank.pytests/skimage/filters/test_edges.pytests/skimage/filters/test_fft_based.pytests/skimage/filters/test_gaussian.pytests/skimage/filters/test_median.pytests/skimage/filters/test_thresholding.pytests/skimage/filters/test_unsharp_mask.pytests/skimage/future/test_trainable_segmentation.pytests/skimage/graph/test_mcp.pytests/skimage/graph/test_pixel_graph.pytests/skimage/io/test_imread.pytests/skimage/io/test_pil.pytests/skimage/io/test_tifffile.pytests/skimage/measure/test_ccomp.pytests/skimage/measure/test_find_contours.pytests/skimage/measure/test_fit.pytests/skimage/measure/test_moments.pytests/skimage/metrics/test_simple_metrics.pytests/skimage/metrics/test_structural_similarity.pytests/skimage/morphology/test_flood_fill.pytests/skimage/morphology/test_misc.pytests/skimage/morphology/test_skeletonize.pytests/skimage/registration/test_ilk.pytests/skimage/registration/test_masked_phase_cross_correlation.pytests/skimage/registration/test_tvl1.pytests/skimage/restoration/test_denoise.pytests/skimage/restoration/test_inpaint.pytests/skimage/restoration/test_j_invariant.pytests/skimage/restoration/test_restoration.pytests/skimage/segmentation/test_boundaries.pytests/skimage/segmentation/test_chan_vese.pytests/skimage/segmentation/test_quickshift.pytests/skimage/segmentation/test_random_walker.pytests/skimage/segmentation/test_slic.pytests/skimage/segmentation/test_watershed.pytests/skimage/transform/test_geometric.pytests/skimage/transform/test_hough_transform.pytests/skimage/transform/test_integral.pytests/skimage/transform/test_pyramids.pytests/skimage/transform/test_radon_transform.pytests/skimage/transform/test_warps.pytests/skimage/util/test_dtype.pytests/skimage/util/test_map_array.pytests/skimage/util/test_montage.pytests/skimage/util/test_random_noise.pytests/skimage/util/test_slice_along_axes.py
| # test result depends on this seed and RNG | ||
| rng = np.random.default_rng(583428449) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify whether this file still mixes Generator- and RandomState-based RNGs.
rg -n 'np\.random\.(default_rng|RandomState)\(' tests/skimage/segmentation/test_quickshift.pyRepository: scikit-image/scikit-image
Length of output: 161
Use RandomState here as well.
Line 38 uses np.random.default_rng while other tests in this file use np.random.RandomState, creating an inconsistency that conflicts with the suite-wide switch to standardize RNG usage.
Suggested diff
- rng = np.random.default_rng(583428449)
+ rng = np.random.RandomState(583428449)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # test result depends on this seed and RNG | |
| rng = np.random.default_rng(583428449) | |
| # test result depends on this seed and RNG | |
| rng = np.random.RandomState(583428449) |
There was a problem hiding this comment.
Per the comment I added this line, the test result depends on this exact seed and RNG stream, so I can't change it.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 72843a89-828d-4e5a-8145-7f1d65ac2267
📒 Files selected for processing (5)
tests/skimage/feature/test_fisher_vector.pytests/skimage/filters/test_edges.pytests/skimage/filters/test_thresholding.pytests/skimage/filters/test_unsharp_mask.pytests/skimage/graph/test_mcp.py
🚧 Files skipped from review as they are similar to previous changes (2)
- tests/skimage/filters/test_thresholding.py
- tests/skimage/filters/test_edges.py
There was a problem hiding this comment.
🧹 Nitpick comments (4)
tests/skimage/measure/test_fit.py (4)
741-743: Prefix unused unpacked variable with underscore.The
rngvariable is unpacked but never used sinceseedis now passed toransac(). Per Python convention and static analysis hints, prefix it with_.Suggested fix
def test_ransac_geometric(ransac_params): - src, dst, model0, outliers, rng, seed = ransac_params + src, dst, model0, outliers, _rng, seed = ransac_params # estimate parameters of corrupted data model_est, inliers = ransac((src, dst), AffineTransform, 2, 20, rng=seed)
752-778: Prefix unused unpacked variables with underscores.Multiple unpacked variables (
outliers,rng,inliers) are unused in this test function.Suggested fix
def test_custom_estimate_warning(ransac_params): # Test that custom estimate class raises warning. - src, dst, model0, outliers, rng, seed = ransac_params + src, dst, model0, _outliers, _rng, seed = ransac_params ... with pytest.warns(FutureWarning, match=msg) as record: - model_est, inliers = ransac((src, dst), C, 2, 20, rng=seed) + model_est, _inliers = ransac((src, dst), C, 2, 20, rng=seed)
797-833: Prefix unused unpacked variables with underscores.In
test_ransac_model_class_protocolandtest_custom_from_estimate_classmethod, variablesmodel0,outliers, andrngare unpacked but never used.Suggested fix
def test_ransac_model_class_protocol(ransac_params): # Test custom classes that don't match protocol. - src, dst, model0, outliers, rng, seed = ransac_params + src, dst, _model0, _outliers, _rng, seed = ransac_params ... def test_custom_from_estimate_classmethod(ransac_params): # Test assertion that custom class `from_estimate` is class method. - src, dst, model0, outliers, rng, seed = ransac_params + src, dst, _model0, _outliers, _rng, seed = ransac_params
1038-1047: Consider adding a seed to theransaccall for full determinism.The
ransaccall doesn't specify anrngparameter. While the test uses all 100 samples (min_samples=100) which should make the result deterministic regardless, addingrng=<seed>would align with the PR's goal of avoiding global RNG state.Suggested fix
model, inliers = ransac( (src, dst), PolynomialTransform, min_samples=100, residual_threshold=1.0, max_trials=1000, model_kwargs={'order': order}, + rng=1, )
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3a7bd9d2-2acd-4b37-b719-3763a21d5e00
📒 Files selected for processing (3)
tests/skimage/graph/test_mcp.pytests/skimage/measure/test_fit.pytests/skimage/util/test_random_noise.py
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/skimage/graph/test_mcp.py
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
tests/skimage/transform/test_geometric.py (2)
77-77: Keep this parametrized input self-contained.
MODULE_RNGis still shared mutable state at module scope. If another draw is added anywhere before this parametrized list, thisProjectiveTransformcase silently changes during collection. A one-off seeded RNG at the use site, or a hard-coded generated matrix, keeps the seed attached to the test input.♻️ Suggested change
-MODULE_RNG = np.random.RandomState(3122886800) @@ - ProjectiveTransform(matrix=MODULE_RNG.rand(3, 3)), + ProjectiveTransform( + matrix=np.random.RandomState(3122886800).rand(3, 3) + ),Also applies to: 959-959
123-127: Avoid the degenerate zero-scale case here.
rng.randint(0, 20)can produce0, which makes the similarity-transform branch singular and the recovered rotation/scale non-unique. The current seed may avoid it, but any extra RNG draw earlier in this test would shift the stream and make this case brittle.♻️ Suggested change
- scale = rng.randint(0, 20) + scale = rng.randint(1, 20)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 94b57e17-b898-4b36-84ae-f278b2019b19
📒 Files selected for processing (11)
CONTRIBUTING.rstsrc/skimage/feature/_fisher_vector.pytests/skimage/feature/test_fisher_vector.pytests/skimage/filters/rank/test_rank.pytests/skimage/filters/test_median.pytests/skimage/measure/test_fit.pytests/skimage/metrics/test_simple_metrics.pytests/skimage/metrics/test_structural_similarity.pytests/skimage/registration/test_masked_phase_cross_correlation.pytests/skimage/transform/test_geometric.pytests/skimage/transform/test_integral.py
🚧 Files skipped from review as they are similar to previous changes (3)
- tests/skimage/filters/rank/test_rank.py
- tests/skimage/registration/test_masked_phase_cross_correlation.py
- tests/skimage/metrics/test_simple_metrics.py
| seed = 4201799844 | ||
| model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed) | ||
| ransac(data0, CircleModel, 3, 5, rng=seed) | ||
|
|
There was a problem hiding this comment.
Assert the repeated ransac call instead of discarding it.
Line 714 looks like it is meant to validate deterministic behavior with the same seed, but the result is ignored, so the test never checks that property.
Suggested assertion
seed = 4201799844
model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed)
- ransac(data0, CircleModel, 3, 5, rng=seed)
+ model_est_2, inliers_2 = ransac(data0, CircleModel, 3, 5, rng=seed)
+ assert_almost_equal(model_est.center, model_est_2.center)
+ assert_almost_equal(model_est.radius, model_est_2.radius)
+ assert_array_equal(inliers, inliers_2)As per coding guidelines, "All code should have tests covering all modifications in behavior".
|
I think this is ready for a human reviewer now. Very aware this is a big diff. Let me know if there's anything I can do to ease reviewing. Happy to split this up into chunks if you'd prefer that. |
|
@stefanv I tried showing up at the weekly meeting so I could ask about my PRs but it looks like I'm the only one here. I see this needs a rebase but before I do that I want to make sure that a change like this is OK. Can I get some feedback on how I should proceed to help improve the testing situation for free-threaded Python in Scikit-Image? |
Argh, so sorry about that Nathan; we had some scheduling difficulties with the team, and have been moving meetings around this week. We'll get the calendar back on track for next week. I think local, vs global, seeds are totally fine. Although I'm not sure we need RandomState any more. Tests should pass with any seed, in theory. @lagru any thoughts on this? |
I'm using If the tests don't care about the RNG stream possibly changing in the future, I could probably switch everything to using a seeded |
|
Ah, yes, that's true; can you imagine the chaos if we (NumPy) were to do that 😅 Totally fine the way you have it, OK to seed But, yes, unless @lagru has concerns I think fine to go ahead. |
|
Reviews (1): Last reviewed commit: "Fix some more occurances that have cropp..." | Re-trigger Greptile |
|
Reviews (2): Last reviewed commit: "delete unused constant" | Re-trigger Greptile |
|
@stefanv rebased and ready for review, I think. |
stefanv
left a comment
There was a problem hiding this comment.
Thanks, @ngoldbaum—this was a lot of work!
We can go ahead and merge once the merge conflict is sorted.
@lagru Do you mind looking at the places where I commented; we may have identified some minor test suite issues along the way.
| ransac(data0, CircleModel, 3, 5, rng=1) | ||
| seed = 4201799844 | ||
| model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed) | ||
| ransac(data0, CircleModel, 3, 5, rng=seed) |
There was a problem hiding this comment.
Yeah, this is weird. I changed it so the two instances use different seeds.
| for ndim in range(1, 5): | ||
| xsize = [ | ||
| N, | ||
| ] * 5 |
There was a problem hiding this comment.
Hrm, wonder if we meant to write * ndim here.
There was a problem hiding this comment.
Good point. I didn't notice it until you pointed it out, but ndim is unused in the loop body.
However, with the following change:
diff --git a/tests/skimage/metrics/test_structural_similarity.py b/tests/skimage/metrics/test_structural_similarity.py
index cb803fa31..5bb1959e7 100644
--- a/tests/skimage/metrics/test_structural_similarity.py
+++ b/tests/skimage/metrics/test_structural_similarity.py
@@ -150,7 +150,7 @@ def test_structural_similarity_nD(dtype):
for ndim in range(1, 5):
xsize = [
N,
- ] * 5
+ ] * ndim
X = (rng.rand(*xsize) * 255).astype(dtype)
Y = (rng.rand(*xsize) * 255).astype(dtype)I see test failures:
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05
🤷 leaving it as-is for now but probably worth following up to understand why this is written this way
There was a problem hiding this comment.
I wasn't able to create the issue automatically (permissions blocked). Here's the content ready to file:
Title: Investigate * 5 vs * ndim in test_structural_similarity_nD
Body:
In
tests/skimage/metrics/test_structural_similarity.py,test_structural_similarity_nDconstructs test arrays using* 5instead of* ndim:for ndim in range(1, 5): xsize = [N] * 5 # should this be `* ndim`? X = (rng.rand(*xsize) * 255).astype(dtype) Y = (rng.rand(*xsize) * 255).astype(dtype)
ndimis effectively unused — arrays are always 5-dimensional regardless of the loop variable.Changing
* 5→* ndimcauses failures:FAILED test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05 FAILED test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05 FAILED test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05Questions:
- Was
* 5intentional? If so, what does thendimloop actually exercise?- If it should be
* ndim, the< 0.05threshold likely needs revisiting for lower-dimensional inputs.Noted in PR #8084.
Labels: tests
Tip: You can customize Greptile's behavior for this repo with .greptile/rules and .greptile/config.
There was a problem hiding this comment.
@greptile OK perhaps that's not a feature you have; you do have the permissions: Read and write access to checks, code, commit statuses, issues, and pull requests
There was a problem hiding this comment.
The tool call was blocked by the local execution environment, not GitHub permissions — so unfortunately I still can't create the issue from here. The read/write permissions you're seeing are on the GitHub App side, but this bot's tool access is being restricted at the agent level.
Your best bet is to file it manually using the content from my previous comment. Apologies for the confusion!
| precomputed result in 2d case. | ||
| """ | ||
|
|
||
| # fails with other seeds? |
There was a problem hiding this comment.
I added seed as a parameterized fixture and ran this test for every seed between 0 and 100. It looks like the tests with float dtypes fail for all seeds besides 0.
There was a problem hiding this comment.
Uh oh, that's probably not right. Restoration is quite sensitive, so maybe the test condition is too strict.
| @pytest.mark.parametrize('ndim', [1, 2, 3]) | ||
| def test_richardson_lucy(ndim, test_root_dir): | ||
| psf = np.ones([5] * ndim, dtype=float) / 5**ndim | ||
| # fails with different seeds? |
There was a problem hiding this comment.
It looks like this one fails for ndim=2 for all seeds besides zero.
| # test result depends on this seed and RNG | ||
| rng = np.random.default_rng(583428449) |
|
Reviews (3): Last reviewed commit: "Merge branch 'main' into local-rng" | Re-trigger Greptile |
| ransac(data0, CircleModel, 3, 5, rng=1) | ||
| seed = 4201799844 | ||
| model_est, inliers = ransac(data0, CircleModel, 3, 5, rng=seed) | ||
| ransac(data0, CircleModel, 3, 5, rng=seed) |
There was a problem hiding this comment.
Yeah, this is weird. I changed it so the two instances use different seeds.
| for ndim in range(1, 5): | ||
| xsize = [ | ||
| N, | ||
| ] * 5 |
There was a problem hiding this comment.
Good point. I didn't notice it until you pointed it out, but ndim is unused in the loop body.
However, with the following change:
diff --git a/tests/skimage/metrics/test_structural_similarity.py b/tests/skimage/metrics/test_structural_similarity.py
index cb803fa31..5bb1959e7 100644
--- a/tests/skimage/metrics/test_structural_similarity.py
+++ b/tests/skimage/metrics/test_structural_similarity.py
@@ -150,7 +150,7 @@ def test_structural_similarity_nD(dtype):
for ndim in range(1, 5):
xsize = [
N,
- ] * 5
+ ] * ndim
X = (rng.rand(*xsize) * 255).astype(dtype)
Y = (rng.rand(*xsize) * 255).astype(dtype)I see test failures:
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[uint8] - assert np.float64(0.12033917126639686) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float32] - assert np.float64(0.12066029480774887) < 0.05
FAILED tests/skimage/metrics/test_structural_similarity.py::test_structural_similarity_nD[float64] - assert np.float64(0.12066033348447812) < 0.05
🤷 leaving it as-is for now but probably worth following up to understand why this is written this way
| precomputed result in 2d case. | ||
| """ | ||
|
|
||
| # fails with other seeds? |
There was a problem hiding this comment.
I added seed as a parameterized fixture and ran this test for every seed between 0 and 100. It looks like the tests with float dtypes fail for all seeds besides 0.
| @pytest.mark.parametrize('ndim', [1, 2, 3]) | ||
| def test_richardson_lucy(ndim, test_root_dir): | ||
| psf = np.ones([5] * ndim, dtype=float) / 5**ndim | ||
| # fails with different seeds? |
There was a problem hiding this comment.
It looks like this one fails for ndim=2 for all seeds besides zero.
| # test result depends on this seed and RNG | ||
| rng = np.random.default_rng(583428449) |
There was a problem hiding this comment.
Per the comment I added this line, the test result depends on this exact seed and RNG stream, so I can't change it.
|
Reviews (4): Last reviewed commit: "use different RNGs in test_ransac_shape" | Re-trigger Greptile |
|
Reviews (5): Last reviewed commit: "Merge branch 'main' into local-rng" | Re-trigger Greptile |
|
That was a big one; thanks Nathan. |
* origin/main: Port tests for `features.canny` to skimage2 (#8126) Replace NumPy global RNG use in tests with local seeded RNGs (#8084) Disable tests using matplotlib on pyodide (#8082) Test with pythonoptimize (#8108) Add skimage2 porting decorator (#8114) Drop 3.13t builds from cibuildwheel configuration (#8127) Restore wording of AI policy (#8123)
Replace the module-level NumPy global RNG state in the skimage2 structural similarity tests with per-test local RNGs so the tests can run under pytest-run-parallel. Use np.random.RandomState (per the pattern established in scikit-image#8084) to keep the reference values that cam_noisy depends on stable. Resolves the merge conflict in test_structural_similarity_dtype and addresses the review on scikit-image#8196.
Replace the module-level NumPy global RNG state in the skimage2 structural similarity tests with per-test local RNGs so the tests can run under pytest-run-parallel. Use np.random.RandomState (per the pattern established in scikit-image#8084) to keep the reference values that cam_noisy depends on stable. Resolves the merge conflict in test_structural_similarity_dtype and addresses the review on scikit-image#8196.
Description
Updates the test suite to prefer explicitly seeded RNGs local to each test.
I'm using
np.random.RandomStateinstead ofnp.random.default_rngbecauseRandomStatehas stronger backward compatibility guarantees, which makes it more suitable for long-term use in a test suite.There were a few cases where I found tests would only pass with specific seeds or RNG streams, and I left comments for those cases.
See https://github.com/numpy/numpy/pull/29729/changes where we did a similar change for NumPy.
Checklist
./doc/examplesfor new featuresRelease note
For maintainers and optionally contributors, please refer to the instructions on how to document this PR for the release notes.