Skip to content

Fix/random seed unwrap - #8099

Closed
michaelbratsch wants to merge 4 commits into
scikit-image:mainfrom
michaelbratsch:fix/random_seed_unwrap
Closed

michaelbratsch wants to merge 4 commits into
scikit-image:mainfrom
michaelbratsch:fix/random_seed_unwrap

Conversation

@michaelbratsch

Copy link
Copy Markdown
Contributor

Description

  • Fix seed initialization in unwrap
  • Fix support np.random.Generator in unwrap

Relates to: #7964

Release note

For maintainers and optionally contributors, please refer to the instructions on how to document this PR for the release notes.

Fix seed initialization in `unwrap`

@greptile-apps

greptile-apps Bot commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

Last reviewed commit: "Add unit test"

Comment thread src/skimage/restoration/unwrap.py Resolved
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

Last reviewed commit: "Cover full range of ..."

Comment on lines +101 to +102
else:
seed = int(rng)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 No range validation for integer seeds

seed = int(rng) succeeds for any Python int, but the C layer declares cseed as unsigned int. If rng is negative or greater than np.iinfo(np.uint32).max (4 294 967 295), Cython will raise an unhelpful OverflowError: value too large to convert to unsigned int (or a negative-value equivalent) deep inside the Cython call rather than at the Python layer with a meaningful message.

The docstring now says "If an int, it is used directly as the seed", which implies any Python int is valid — but the valid range is silently constrained to [0, 2^32-1]. Consider adding explicit validation here:

else:
    seed = int(rng)
    if not 0 <= seed <= np.iinfo(np.uint32).max:
        raise ValueError(
            f"Integer seed must be in [0, {np.iinfo(np.uint32).max}], got {seed}"
        )

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this Greptile change is reasonable - do you agree?

@matthew-brett matthew-brett Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I'll add a version of Greptile's suggestion - I think it is reasonable. It would also be good to have a test for this behavior.

See suggestion above for changes.

@lagru
lagru self-requested a review March 20, 2026 17:39

@matthew-brett matthew-brett left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion and suggestion on suggestion.

Comment on lines +31 to +35
Seed for the random number generator used during unwrapping.
If an int, it is used directly as the seed. If a
`numpy.random.Generator`, a seed is drawn from it. If `None`,
unwrapping relies on a random initialization and results may vary
between runs.

@matthew-brett matthew-brett Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Seed for the random number generator used during unwrapping.
If an int, it is used directly as the seed. If a
`numpy.random.Generator`, a seed is drawn from it. If `None`,
unwrapping relies on a random initialization and results may vary
between runs.
Unwrapping relies on a random initialization. `rng` supplies the
source of a seed for the C-level random number generator used during
unwrapping. If an int, it is used directly as the seed; in that case,
it should be in the range of a C unsigned integer. If a
`numpy.random.Generator`, we draw a suitable integer from the generator
to use as the seed. If ``None``, create a new (unseeded)
`numpy.random.Generator` from which to draw the seed.

Comment on lines +101 to +102
else:
seed = int(rng)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this Greptile change is reasonable - do you agree?

@matthew-brett matthew-brett left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple more comments on reflection.

Comment on lines +101 to +102
else:
seed = int(rng)

@matthew-brett matthew-brett Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I'll add a version of Greptile's suggestion - I think it is reasonable. It would also be good to have a test for this behavior.

See suggestion above for changes.

@matthew-brett

Copy link
Copy Markdown
Contributor

And - on reflection - at the moment, with None we simply do not seed the C random number generator. But this does not result in random initialization, it results in the equivalent of srand(1): https://en.cppreference.com/c/numeric/random/srand - so - predictable random numbers. It seems to me that it would be better to do something like:

    if rng is None:
        rng = np.random.default_rng()

and draw a random seed from there.

@matthew-brett

Copy link
Copy Markdown
Contributor

@michaelbratsch - sorry to press you - but do you have any thoughts here? If you're busy, I'm happy to take this one over (and give you due credit).

@matthew-brett matthew-brett left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rethinking approach a little. Always pass a seed, but perhaps from a new random generator.


# convert from python types to C types so we can release the GIL
use_seed = seed is None
use_seed = seed is not None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can drop this check with the changes below (we always specify a seed, but the seed might be random).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And therefore remove use_seed in calls to unwrap2D and unwrap3D functions.


# convert from python types to C types so we can release the GIL
use_seed = seed is None
use_seed = seed is not None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above.

Comment on lines +97 to +102
if isinstance(rng, np.random.Generator):
seed = int(rng.integers(np.iinfo(np.uint32).max, endpoint=True))
elif rng is None:
seed = None
else:
seed = int(rng)

@matthew-brett matthew-brett May 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if isinstance(rng, np.random.Generator):
seed = int(rng.integers(np.iinfo(np.uint32).max, endpoint=True))
elif rng is None:
seed = None
else:
seed = int(rng)
if rng is None: # Use new generator to make seed.
rng = np.random.default_rng()
# Algorithms use C `srand(seed)` to initialize random stream from
# subsequent calls to `rand()`. `srand` expects an unsigned C int.
uintc_max = np.iinfo(np.uintc).max
if isinstance(rng, np.random.Generator):
seed = rng.integers(uintc_max, endpoint=True)
else:
try:
seed = np.uintc(rng)
except OverflowError:
raise ValueError(
f"Integer seed must be in [0, {uintc_max}], got {rng}"
)

)
# For `None` the behavior is not deterministic, so it does not make sense to check
# for equality. At least call it to see that `None` is an accepted value.
unwrap(None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check that result differs from call to call with None?

@matthew-brett

Copy link
Copy Markdown
Contributor

Sorry for my impatience, but I also wanted to refactor for better thread safety. Take-over PR at #8142 .

stefanv added a commit that referenced this pull request May 14, 2026
This is a continuation of #8099

It includes:

- @michaelbratsch's fixes to random seeding
- Port to using NumPy RNG for random number generation, for better
  thread-safety.
- Use intptr_t for variables containing array sizes or indices.
- Some variable renaming for clarity, and removal of a TODO cleared up
  by the variable renaming.
- Refactor of common code in 2D and 3D .c files into a new
  unwrap_common.h header file.
- Added back sentinel large initial value for pixels / voxels for
  which we cannot calculate unreliability scores. This is from the
  original code before inclusion in scikit-image.

---
Co-authored-by: Michael Bratsch <[email protected]>
Co-authored-by: Stefan van der Walt <[email protected]>
@michaelbratsch

Copy link
Copy Markdown
Contributor Author

Sorry for my impatience, but I also wanted to refactor for better thread safety. Take-over PR at #8142 .

I honestly lost track of this merge request because there has been no feedback for quite a long time. Nice to see that it eventually has been used and got in some form into the main branch.

@lagru

lagru commented May 16, 2026

Copy link
Copy Markdown
Member

[...] because there has been no feedback for quite a long time.

Sorry for that! 🙈

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.

3 participants