Skip to content

[Data] Improve reproducibility for random APIs - #59662

Merged
goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
wingkitlee0:kit/reproducibility
Mar 18, 2026
Merged

goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
wingkitlee0:kit/reproducibility

Conversation

@wingkitlee0

@wingkitlee0 wingkitlee0 commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Description

This PR introduces RandomSeedConfig to handle random number generation initialization in random_* APIs and allow extra options for reproducibility across pipeline re-executions (e.g., training epochs). The class is modeled after FileShuffleConfig which uses DataContext._execution_idx as an extra seed.

When RandomSeedConfig(seed, reseed_after_execution=True) is set, the random ops will be re-seeded after each execution. This means that for random_* APIs, the results will be different for a new call to iter_*_batches APIs (i.e., DataIterator). In terms of model training, this means the data will be shuffle differently for each epoch, even when a initial random seed is set.

Changes

  • the following APIs now accept a RandomSeedConfig object as seed:
    • random_sample()
    • random_shuffle()
    • randomize_block_order()

Related issues

Closes #55275

Additional information

Implementation

  • Numpy's default_rng() takes an integer or a tuple of them. So when reseed_after_execution is set, we use (execution_idx, base_seed) to initialize. This needs to happens somewhere lower-level in Ray Data that is re-run during multiple execution.
  • The seed tuple remains "deterministic" as the execution_idx is incremented by 1 each time the pipeline gets rerun. This in principle allows the multiple-epoch model training to be reproducible (minus other usual things that affect reproducibility, e.g., ordering, cluster configs, etc)
  • This PR consolidates the seed argument. So the original integer/None seed is wrapped inside RandomSeedConfig before passing into the op definitions. In principle, we could make a default value of reseed_after_execution in DataContext to control all seed handling at once.

Example

When reseed_after_execution is set to True, re-execution of the pipeline (second line) will return different results.

ds = ray.data.range(10)
ds.random_shuffle(seed=RandomSeedConfig(1234, reseed_after_execution=True)).take_all()

Setting reseed_after_execution to False (or use integer seed directly) will produce the same (random) result when the pipeline is executed multiple times.

Notes

  • For a materialized Ray Dataset (i.e., materialize() is called), there is no effect as the pipeline is not re-executed in this case.
  • There are a few other APIs with seed argument that I didn't touch.

@wingkitlee0 wingkitlee0 changed the title Kit/reproducibility [Data] Improve reproducibility for random APIs Dec 25, 2025

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request refactors the handling of random seeds in Ray Data to improve reproducibility. It introduces a new RandomSeedConfig dataclass to encapsulate seeding logic, which is then used across various random operations like random_shuffle, randomize_block_order, and random_sample. This change centralizes the seeding logic, making it more consistent and maintainable. The FileShuffleConfig is also updated to inherit from RandomSeedConfig, reducing code duplication. The changes are well-implemented and enhance the framework's reproducibility features. My main feedback is to generalize the docstrings in the new random_config.py file to reflect its broad usage beyond just file shuffling.

@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch 5 times, most recently from fd0765e to 44e3234 Compare December 25, 2025 22:42
@wingkitlee0

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no bugs!

@wingkitlee0 wingkitlee0 added go add ONLY when ready to merge, run all tests data Ray Data-related issues labels Dec 25, 2025
@wingkitlee0
wingkitlee0 marked this pull request as ready for review December 26, 2025 02:54
@wingkitlee0
wingkitlee0 requested a review from a team as a code owner December 26, 2025 02:54
@wingkitlee0 wingkitlee0 added the community-contribution Contributed by the community label Dec 27, 2025
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jan 11, 2026
@wingkitlee0

Copy link
Copy Markdown
Contributor Author

unstale

@wingkitlee0 wingkitlee0 removed the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jan 11, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jan 25, 2026
@wingkitlee0

Copy link
Copy Markdown
Contributor Author

unstale please

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Jan 26, 2026
@iamjustinhsu
iamjustinhsu self-requested a review February 4, 2026 18:23
@iamjustinhsu iamjustinhsu self-assigned this Feb 4, 2026

@iamjustinhsu iamjustinhsu 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.

nice work

seed_config: RandomSeedConfig,
data_context: DataContext,
*,
use_timestamp_as_default: bool,

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.

what are your thoughts on adding use_timestamp_as_default to RandomSeedConfig, and then in randomize_blocks() or random_shuffle() we generate the RandomSeedConfig with use_timestamp_as_default=False/True

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point. I have cleared some logic around this parameter in this and other functions as well, which are only used for "backward compatibility".

return (self.seed,)

@classmethod
def _normalize_seed_argument(

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.

do u think it would be better to rename to something like create?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated.

@classmethod
def _normalize_seed_argument(
cls,
seed: Optional[Union[int, "RandomSeedConfig"]],

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.

Since moving to python3.10, i think we now support the | syntax. There is no style guide for this, but thoughts on making it int | RandomSeedConfig | None? I just find it a bit more readable

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It turns out I can't use str with | here. So I fixed it by from __future__ import annotations

Ray Data API.

Args:
seed: A seed argument accepted by the Ray Data API.

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 should be a bit more descriptive

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated the docstring

@wingkitlee0

Copy link
Copy Markdown
Contributor Author

@iamjustinhsu thanks for the review. I will come back to address your comments (and conflicts) when I get a chance.

@wingkitlee0

Copy link
Copy Markdown
Contributor Author

Hi @iamjustinhsu @richardliaw , let me know if there are more comments or if this can be merged. Thanks so much for reviewing!

FYI, there was another PR closed for this: #61426

return seed_tuple[0]

# Modulo ensures the result is in valid NumPy seed range [0, 2**32 - 1].
return hash(seed_tuple) % (2**32)

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.

Can we make this a const?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed

self,
*,
data_context: DataContext,
) -> tuple[int] | tuple[int, int] | 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.

Can we use a dataclass instead?

@goutamvenkat-anyscale goutamvenkat-anyscale Mar 16, 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.

Return type should be something like int | ExecutionIdSeed

@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch from 9884964 to ffe42fc Compare March 17, 2026 01:34
Comment thread python/ray/data/dataset.py Resolved
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch 3 times, most recently from 56465bc to 1958211 Compare March 17, 2026 03:36
@wingkitlee0
wingkitlee0 requested a review from a team as a code owner March 17, 2026 03:43
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch 2 times, most recently from ee7fb67 to a446d07 Compare March 17, 2026 04:19
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch 2 times, most recently from a3282bf to 0ffebb9 Compare March 17, 2026 12:15
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch from 4433dae to c589130 Compare March 17, 2026 22:47

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

We set use_timestamp_as_default=True to pin the seed at plan time
so that retried shuffle tasks produce the same output.
See ray-project#50924.

Signed-off-by: Kit Lee <[email protected]>
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch from c589130 to 1ebfccc Compare March 17, 2026 23:15
@wingkitlee0
wingkitlee0 force-pushed the kit/reproducibility branch from b6c95d7 to 2896e68 Compare March 17, 2026 23:55
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 5ca80bb into ray-project:master Mar 18, 2026
3 checks passed
richardliaw pushed a commit that referenced this pull request Mar 24, 2026
## Description

Adding two new expressions:
* `random()` for generating a column of uniform random number.
* `uuid()` for generating UUID (a column of unique strings)

`random()` accepts two arguments, related to reproducibility:
* `seed`: a "base" random seed. Default is `None`.
* `reseed_after_execution`: This is a flag that affects the random
number generation across different iteration of `iter_batches` (i.e.,
across different epochs in the context of epochs). See also,
#59528. It only matters when the
`seed` is set. If False, each dataset execution will generate the same
set of random number. If True, each dataset execution (i.e., training
epoch) will give a new but reproducible set of random number.

`uuid()` takes no argument.

## Related issues
Related to #55275

Related to #59662 as well. I did this PR first...so probably I could use
the same `RandomSeedConfig` in that PR.

## Additional information

[Random seed business] The actual seed sequence used to initialize the
random number generator is `[block_idx, task_idx, execution_idx,
base_seed]`. The block idx is tracked by a counter (like in
`monotonically_increasing_id()`). The task and execution indices are
coming from `TaskContext` and `DataContext`, respectively. The way I
used `execution_idx` is slightly different to what `FileShuffleConfig`
is doing, but I think all these random seed business could be
consolidated in the future (e.g., random_sample)

[Independent visit functions] Following the discussion in
#59290, there are separate
`visit_uuid()` and `visit_random` for these expressions.

Signed-off-by: Kit Lee <[email protected]>
ryanaoleary pushed a commit to ryanaoleary/ray that referenced this pull request Mar 25, 2026
## Description

This PR introduces `RandomSeedConfig` to handle random number generation
initialization in `random_*` APIs and allow extra options for
reproducibility across pipeline re-executions (e.g., training epochs).
The class is modeled after `FileShuffleConfig` which uses
`DataContext._execution_idx` as an extra seed.

When `RandomSeedConfig(seed, reseed_after_execution=True)` is set, the
random ops will be re-seeded after each execution. This means that for
random_* APIs, the results will be different for a new call to
`iter_*_batches` APIs (i.e., `DataIterator`). In terms of model
training, this means the data will be shuffle differently for each
epoch, even when a initial random seed is set.

### Changes
* the following APIs now accept a `RandomSeedConfig` object as `seed`:
  * `random_sample()`
  * `random_shuffle()`
  * `randomize_block_order()`

## Related issues
Closes ray-project#55275

## Additional information
### Implementation

* Numpy's `default_rng()` takes an integer or a tuple of them. So when
`reseed_after_execution` is set, we use `(execution_idx, base_seed)` to
initialize. This needs to happens somewhere lower-level in Ray Data that
is re-run during multiple execution.
* The seed tuple remains "deterministic" as the `execution_idx` is
incremented by 1 each time the pipeline gets rerun. This in principle
allows the multiple-epoch model training to be reproducible (minus other
usual things that affect reproducibility, e.g., ordering, cluster
configs, etc)
* This PR consolidates the `seed` argument. So the original integer/None
seed is wrapped inside `RandomSeedConfig` before passing into the op
definitions. In principle, we could make a default value of
`reseed_after_execution` in `DataContext` to control all seed handling
at once.

### Example

When `reseed_after_execution` is set to True, re-execution of the
pipeline (second line) will return different results.
```python
ds = ray.data.range(10)
ds.random_shuffle(seed=RandomSeedConfig(1234, reseed_after_execution=True)).take_all()
```
Setting `reseed_after_execution` to `False` (or use integer seed
directly) will produce the same (random) result when the pipeline is
executed multiple times.

### Notes
* For a materialized Ray Dataset (i.e., `materialize()` is called),
there is no effect as the pipeline is not re-executed in this case.
* There are a few other APIs with `seed` argument that I didn't touch.

---------

Signed-off-by: Kit Lee <[email protected]>
ryanaoleary pushed a commit to ryanaoleary/ray that referenced this pull request Mar 25, 2026
## Description

Adding two new expressions:
* `random()` for generating a column of uniform random number.
* `uuid()` for generating UUID (a column of unique strings)

`random()` accepts two arguments, related to reproducibility:
* `seed`: a "base" random seed. Default is `None`.
* `reseed_after_execution`: This is a flag that affects the random
number generation across different iteration of `iter_batches` (i.e.,
across different epochs in the context of epochs). See also,
ray-project#59528. It only matters when the
`seed` is set. If False, each dataset execution will generate the same
set of random number. If True, each dataset execution (i.e., training
epoch) will give a new but reproducible set of random number.

`uuid()` takes no argument.

## Related issues
Related to ray-project#55275

Related to ray-project#59662 as well. I did this PR first...so probably I could use
the same `RandomSeedConfig` in that PR.

## Additional information

[Random seed business] The actual seed sequence used to initialize the
random number generator is `[block_idx, task_idx, execution_idx,
base_seed]`. The block idx is tracked by a counter (like in
`monotonically_increasing_id()`). The task and execution indices are
coming from `TaskContext` and `DataContext`, respectively. The way I
used `execution_idx` is slightly different to what `FileShuffleConfig`
is doing, but I think all these random seed business could be
consolidated in the future (e.g., random_sample)

[Independent visit functions] Following the discussion in
ray-project#59290, there are separate
`visit_uuid()` and `visit_random` for these expressions.

Signed-off-by: Kit Lee <[email protected]>
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
## Description

This PR introduces `RandomSeedConfig` to handle random number generation
initialization in `random_*` APIs and allow extra options for
reproducibility across pipeline re-executions (e.g., training epochs).
The class is modeled after `FileShuffleConfig` which uses
`DataContext._execution_idx` as an extra seed.

When `RandomSeedConfig(seed, reseed_after_execution=True)` is set, the
random ops will be re-seeded after each execution. This means that for
random_* APIs, the results will be different for a new call to
`iter_*_batches` APIs (i.e., `DataIterator`). In terms of model
training, this means the data will be shuffle differently for each
epoch, even when a initial random seed is set.

### Changes
* the following APIs now accept a `RandomSeedConfig` object as `seed`:
  * `random_sample()`
  * `random_shuffle()`
  * `randomize_block_order()`

## Related issues
Closes ray-project#55275

## Additional information
### Implementation

* Numpy's `default_rng()` takes an integer or a tuple of them. So when
`reseed_after_execution` is set, we use `(execution_idx, base_seed)` to
initialize. This needs to happens somewhere lower-level in Ray Data that
is re-run during multiple execution.
* The seed tuple remains "deterministic" as the `execution_idx` is
incremented by 1 each time the pipeline gets rerun. This in principle
allows the multiple-epoch model training to be reproducible (minus other
usual things that affect reproducibility, e.g., ordering, cluster
configs, etc)
* This PR consolidates the `seed` argument. So the original integer/None
seed is wrapped inside `RandomSeedConfig` before passing into the op
definitions. In principle, we could make a default value of
`reseed_after_execution` in `DataContext` to control all seed handling
at once.

### Example

When `reseed_after_execution` is set to True, re-execution of the
pipeline (second line) will return different results.
```python
ds = ray.data.range(10)
ds.random_shuffle(seed=RandomSeedConfig(1234, reseed_after_execution=True)).take_all()
```
Setting `reseed_after_execution` to `False` (or use integer seed
directly) will produce the same (random) result when the pipeline is
executed multiple times.

### Notes
* For a materialized Ray Dataset (i.e., `materialize()` is called),
there is no effect as the pipeline is not re-executed in this case.
* There are a few other APIs with `seed` argument that I didn't touch.

---------

Signed-off-by: Kit Lee <[email protected]>
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
## Description

Adding two new expressions:
* `random()` for generating a column of uniform random number.
* `uuid()` for generating UUID (a column of unique strings)

`random()` accepts two arguments, related to reproducibility:
* `seed`: a "base" random seed. Default is `None`.
* `reseed_after_execution`: This is a flag that affects the random
number generation across different iteration of `iter_batches` (i.e.,
across different epochs in the context of epochs). See also,
ray-project#59528. It only matters when the
`seed` is set. If False, each dataset execution will generate the same
set of random number. If True, each dataset execution (i.e., training
epoch) will give a new but reproducible set of random number.

`uuid()` takes no argument.

## Related issues
Related to ray-project#55275

Related to ray-project#59662 as well. I did this PR first...so probably I could use
the same `RandomSeedConfig` in that PR.

## Additional information

[Random seed business] The actual seed sequence used to initialize the
random number generator is `[block_idx, task_idx, execution_idx,
base_seed]`. The block idx is tracked by a counter (like in
`monotonically_increasing_id()`). The task and execution indices are
coming from `TaskContext` and `DataContext`, respectively. The way I
used `execution_idx` is slightly different to what `FileShuffleConfig`
is doing, but I think all these random seed business could be
consolidated in the future (e.g., random_sample)

[Independent visit functions] Following the discussion in
ray-project#59290, there are separate
`visit_uuid()` and `visit_random` for these expressions.

Signed-off-by: Kit Lee <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data/Train/Doc] Improve reproducibility

4 participants