Repository navigation
[Data] Improve reproducibility for random APIs - #59662
Conversation
There was a problem hiding this comment.
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.
fd0765e to
44e3234
Compare
|
bugbot run |
|
This pull request has been automatically marked as stale because it has not had 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. |
|
unstale |
|
This pull request has been automatically marked as stale because it has not had 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. |
|
unstale please |
| seed_config: RandomSeedConfig, | ||
| data_context: DataContext, | ||
| *, | ||
| use_timestamp_as_default: bool, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
do u think it would be better to rename to something like create?
| @classmethod | ||
| def _normalize_seed_argument( | ||
| cls, | ||
| seed: Optional[Union[int, "RandomSeedConfig"]], |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
I think this should be a bit more descriptive
There was a problem hiding this comment.
Updated the docstring
|
@iamjustinhsu thanks for the review. I will come back to address your comments (and conflicts) when I get a chance. |
fc33eec to
c630aaf
Compare
|
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) |
There was a problem hiding this comment.
Can we make this a const?
| self, | ||
| *, | ||
| data_context: DataContext, | ||
| ) -> tuple[int] | tuple[int, int] | None: |
There was a problem hiding this comment.
Can we use a dataclass instead?
There was a problem hiding this comment.
Return type should be something like int | ExecutionIdSeed
9884964 to
ffe42fc
Compare
56465bc to
1958211
Compare
ee7fb67 to
a446d07
Compare
a3282bf to
0ffebb9
Compare
4433dae to
c589130
Compare
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]>
c589130 to
1ebfccc
Compare
Signed-off-by: Kit Lee <[email protected]>
Signed-off-by: Kit Lee <[email protected]>
b6c95d7 to
2896e68
Compare
## 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]>
## 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]>
## 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]>
## 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]>
## 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]>

Description
This PR introduces
RandomSeedConfigto handle random number generation initialization inrandom_*APIs and allow extra options for reproducibility across pipeline re-executions (e.g., training epochs). The class is modeled afterFileShuffleConfigwhich usesDataContext._execution_idxas 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 toiter_*_batchesAPIs (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
RandomSeedConfigobject asseed:random_sample()random_shuffle()randomize_block_order()Related issues
Closes #55275
Additional information
Implementation
default_rng()takes an integer or a tuple of them. So whenreseed_after_executionis 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.execution_idxis 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)seedargument. So the original integer/None seed is wrapped insideRandomSeedConfigbefore passing into the op definitions. In principle, we could make a default value ofreseed_after_executioninDataContextto control all seed handling at once.Example
When
reseed_after_executionis set to True, re-execution of the pipeline (second line) will return different results.Setting
reseed_after_executiontoFalse(or use integer seed directly) will produce the same (random) result when the pipeline is executed multiple times.Notes
materialize()is called), there is no effect as the pipeline is not re-executed in this case.seedargument that I didn't touch.