Repository navigation
[data] Monotonically increasing id - #59290
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces add_unique_id to add a monotonically increasing ID column to a dataset, which is a valuable addition. The implementation is clear and follows the described logic from Spark. However, I've identified a significant correctness issue in the handling of pyarrow.Table objects, which results in creating a nested list column instead of a flat integer column. I've also provided suggestions to improve efficiency, remove unreachable code, and enhance the clarity of the documentation. The tests are well-structured, but they may not be catching the pyarrow bug I've pointed out.
|
awesome! thanks a bunch for this contribution. will let @gvspraveen find someone to shepherd this. |
|
Thanks for the contribution. @bveeramani to shepherd this. |
|
hey @rishic3, thanks a bunch for the contribution! if you're interested in chatting more with the contributors, feel free to join our community sync -- https://docs.google.com/forms/d/e/1FAIpQLSeYWjNExnr6gbhO5rpM0i6wm4TBTdsm3y5S0LR8Syzk_2gelQ/viewform |
|
Previous commit implemented as a dataset method (see e0fc987). Pushed an update that instead implements as an expression as per original issue intended. |
|
Hey @rishic3 , thanks for opening the PR! I'll review first thing tomorrow |
| if ctx is None: | ||
| raise RuntimeError( | ||
| "monotonically_increasing_id() must be evaluated within a Ray task" | ||
| ) |
There was a problem hiding this comment.
Nit: This seems more of an internal correctness assumption. Would this be better as an assertion?
| def visit_monotonically_increasing_id( | ||
| self, expr: "MonotonicallyIncreasingIdExpr" | ||
| ) -> "BooleanExpression | UnboundTerm[Any] | Literal[Any]": | ||
| """Monotonically increasing ID expressions cannot be converted to Iceberg expressions.""" | ||
| raise TypeError( | ||
| "monotonically_increasing_id expressions cannot be converted to Iceberg filter expressions." | ||
| ) |
There was a problem hiding this comment.
Non-blocking for this PR since it's internal, but I'm worried that we'll need to expand the visitor interface each time we introduce a new expression, and that'll become unwieldy.
@goutamvenkat-anyscale what's your take? Is there an easy solution?
There was a problem hiding this comment.
That's exactly the goal of the visitor pattern -- to guarantee that all expressions are being properly handled
| def structurally_equals(self, other: Any) -> bool: | ||
| # Non-deterministic, never structurally equal to another expression | ||
| return False |
There was a problem hiding this comment.
@goutamvenkat-anyscale in Ray Data's context, what does structurally equal mean? I read the docstring but it doesn't really answer my question: """Compare two expression ASTs for structural equality."""
Should two MonotonicallyIncreasingIdExpr be structurally equal?
There was a problem hiding this comment.
Doesn't seem used by optimizer yet but I'm assuming for e.g. common subexpression elimination which we wouldn't want applied to non-deterministic expressions.
|
This expr is the first to depend on TaskContext. Looks like using it with shuffle will fail ds = ray.data.range(10, override_num_blocks=2)
ds = ds.with_column("uid", monotonically_increasing_id())
ds = ds.random_shuffle()
ds.take_all()With (traceback>...as the shuffle schedulers e.g. Quick fix could be wrapping execution of the upstream map fn in the shuffle task spec in a new task context or I suppose the more complete change is creating the task ctx at the scheduler level and changing the downstream functions to accept task ctx.Wondering if this path makes sense or if implementing this as a dedicated operator (like e0fc987) would be preferred to keep expressions independent of task context in the first place. @bveeramani @goutamvenkat-anyscale |
Got it. Will defer to @goutamvenkat-anyscale since he's the resident expressions expert |
| The assumption is that the dataset schedules less than 1 billion tasks, and | ||
| each task processes less than 8 billion records. | ||
|
|
||
| The function is non-deterministic because its result depends on task IDs. |
There was a problem hiding this comment.
Task has to be deterministic assuming its inputs are fixed (and this method is deterministic in that def)
There was a problem hiding this comment.
Agree that it is deterministic at the granularity of a task, though at dataset level task assignment would be non-deterministic - so still seems like right description from user POV?
| # Key the counter by expression instance ID so that multiple expressions | ||
| # in the same projection will have isolated row count state | ||
| counter_key = f"_mono_id_{expr._instance_id}_counter" | ||
|
|
||
| start_idx = ctx.kwargs.get(counter_key, 0) |
There was a problem hiding this comment.
@rishic3 we'd not store state like that inside TaskContext.
Besides -- we don't need to provide a guarantee that 2 expressions will produce different results.
(but even if we did we can do that by just simply shuffling the ids w/in a block)
There was a problem hiding this comment.
we don't need to provide a guarantee that 2 expressions will produce different results
Not quite following - keying by instance ID here so that two expressions don't increment each other's row counts when executed by the same task (so if anything, would ensure in such a case ids are the same)
we'd not store state like that inside TaskContext.
Agree it's not ideal. Was considering making it an instance attribute of MonotonicallyIncreasingIdExpr, though would require it to be stateful (might necessitate a new non-frozen base class).
There was a problem hiding this comment.
@rishic3 my point is -- why do you need start_idx in the TaskContext at all?
- Because every task's range is isolated (via task id bits) you just need to run a counter from 0 to num_rows in every block
- If you want different expressions (which is not a requirement btw) just shuffle row ids
There was a problem hiding this comment.
Correct me if i'm wrong, but my understanding is a single task could process multiple blocks:
For example if I force this behavior by setting max block size to 32 bytes (4 int64 rows per block, across 5 tasks below):
from ray.data.expressions import monotonically_increasing_id
ctx = ray.data.DataContext.get_current()
ctx.target_max_block_size = 32
ds = ray.data.range(100, override_num_blocks=5)
ds = ds.with_column("uid", monotonically_increasing_id())
result = ds.take_all()With a print statement in visit_monotonically_increasing_id this shows
(ReadRange->Project pid=496751) Task ID 2 is starting at start_idx: 0
(ReadRange->Project pid=496751) Task ID 2 is starting at start_idx: 4
(ReadRange->Project pid=496751) Task ID 2 is starting at start_idx: 8
(ReadRange->Project pid=496751) Task ID 2 is starting at start_idx: 12
(ReadRange->Project pid=496751) Task ID 2 is starting at start_idx: 16
so if we were to just run a counter we'd lost monotonicity across these blocks (i.e., these would all start at 0).
There was a problem hiding this comment.
Oh, you're right -- we actually compress into 1 block for file-based datasources but not for all data-sources (which we should btw).
Can you please leave a comment why we're doing this.
Please also add a test for it!
| ids = partition_mask + np.arange( | ||
| start_idx, start_idx + num_rows, dtype=np.int64 | ||
| ) |
There was a problem hiding this comment.
You need to apply mask on the num rows to make sure it's not exceeding 32 bits
There was a problem hiding this comment.
Good point, added exceptions on overflows
|
FYI, I am implementing |
|
@goutamvenkat-anyscale do you mind taking a look when you get the chance? Thanks! |
|
Added task context to shuffle task spec to unblock the shuffle issue, since it looks like other expressions will need it. |
|
@rishic3 @iamjustinhsu @bveeramani @alexeykudinkin @goutamvenkat-anyscale Can you guys take a look of a similar PR (for random and uuid) in #59656 Likely we will need some coordinations (and some decisions from Ray team) |
|
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. |
|
Unstaling. |
Signed-off-by: Rishi Chandra <[email protected]> # Conflicts: # python/ray/data/tests/test_map.py Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
Signed-off-by: Rishi Chandra <[email protected]>
f59185d to
20497d2
Compare
Signed-off-by: Rishi Chandra <[email protected]>
Thanks -- had to add a missing doc in expressions.rst, so went ahead and addressed your comments as well. (Aside, looks like there's an unrelated failure with missing |
## Description Implements monotonically increasing ID expression. This closely follows the Spark implementation https://github.com/apache/spark/blob/9bbdc0743034b40a904ca87a08da4e0bf2b1386c/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/MonotonicallyIncreasingID.scala. Example usage: ```python from ray.data.expressions import monotonically_increasing_id ds = ray.data.range(100) ds = ds.with_column("uid", monotonically_increasing_id()) train, test = ds_with_id.streaming_train_test_split(test_size=0.25, split_type="hash", hash_column="uid") ``` ## Related issues Closes ray-project#57806 --------- Signed-off-by: Alexey Kudinkin <[email protected]> Signed-off-by: Rishi Chandra <[email protected]> Signed-off-by: Adel Nour <[email protected]>
## Description Implements monotonically increasing ID expression. This closely follows the Spark implementation https://github.com/apache/spark/blob/9bbdc0743034b40a904ca87a08da4e0bf2b1386c/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/MonotonicallyIncreasingID.scala. Example usage: ```python from ray.data.expressions import monotonically_increasing_id ds = ray.data.range(100) ds = ds.with_column("uid", monotonically_increasing_id()) train, test = ds_with_id.streaming_train_test_split(test_size=0.25, split_type="hash", hash_column="uid") ``` ## Related issues Closes ray-project#57806 --------- Signed-off-by: Alexey Kudinkin <[email protected]> Signed-off-by: Rishi Chandra <[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, #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 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 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
Implements monotonically increasing ID expression. This closely follows the Spark implementation https://github.com/apache/spark/blob/9bbdc0743034b40a904ca87a08da4e0bf2b1386c/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/MonotonicallyIncreasingID.scala.
Example usage:
Related issues
Closes #57806