[Data] Implement Spark-like accumulators in Ray Data
Description
We propose adding an accumulator to Ray Data to facilitate the computation of various metrics from a data pipeline. This feature will allow users to easily aggregate and compute evaluation metrics from batch inference pipelines like accuracy, cross-entropy loss, AUROC.. without having to reach to Ray Core primitives and implement complex logic.
Use case
Motivation
Currently users need to either:
- Implement their own accumulator logic using Ray Core Actors, for example see the pinterest post on batch inference
- Rely on composing logic in
map_batchesto perform a local aggregation along with ads.aggregatecall. This is not as flexible of a solution especially when:- A user wants to aggregate multiple evaluation metrics - i.e. a single
ds.aggregatecall is not enough. - Dealing with very large datasets given
ds.aggregaterequires materializing all inputs.
- A user wants to aggregate multiple evaluation metrics - i.e. a single
Proposed API
The accumulator can be implemented as a new class, Accumulator, with methods to update values, retrieve the accumulated result, and reset the accumulator. The class can be integrated into the existing Ray Data pipeline, allowing users to specify the metrics they want to compute and automatically aggregating the results as data flows through the pipeline.
Example Usage
from ray.data.accumulator import Accumulator
# Example usage of the Accumulator class in a Ray Data pipeline
# Define a custom accumulator for summing values
class SumAccumulator(Accumulator):
def __init__(self):
self.sum = 0
def update(self, value):
self.sum += value
def get(self):
return self.sum
def reset(self):
self.sum = 0
# Create a dataset
ds = ray.data.read_csv("test.csv")
# Initialize the accumulator
sum_accumulator = SumAccumulator()
# Define a function to process each batch and update the accumulator
def process_batch(batch):
for value in batch["a"]:
sum_accumulator.update(value)
return batch
# Apply the function to the dataset
ds = ds.map_batches(process_batch)
# Retrieve the accumulated result
total_sum = sum_accumulator.get()
print(f"Total sum of column 'a': {total_sum}")
# Reset the accumulator for future use
sum_accumulator.reset()
The user-defined subclasses of Accumulator needs to be an actor (or get converted into one) at some point, right? This is to handle concurrent update() from different underlying ray tasks.
Hey @marwan116 @alexeykudinkin any update on this one?
No updates this is in the backlog
Hi @alexeykudinkin @richardliaw, I'd like to work on this. I saw PR #51404 was closed asking for a design discussion first, and #64221 recently added CustomOpStats. Below is a proposal built on that, plus a small prototype I used to check it. I'd like your feedback before going further. There's no open PR for this today.
The issue's example doesn't work as written. UDFs run in worker processes, so a driver-side object mutated inside map_batches stays unchanged. In a quick test on Ray 2.60.0, the expected sum was 499500 and the driver-side value was 0.
Why not an actor (as in #51404). Each update() is a blocking ray.get. On a local run (20k rows, 8 blocks) a no-op map_batches took 0.11s. One actor RPC per batch took 0.18s, and one per row took 6.67s. An actor also can't tell task attempts apart, so retried tasks would double-count.
Proposal: carry per-task partials in block metadata.
Accumulator.add(v)updates an in-memory partial held on the task'sTaskContext. There is no RPC. The partial is cleared at the start of each task attempt, likeCustomOpStatsReporter._map_tasksnapshots the partials, cumulatively, into a newCustomOpStatssubclass on each block'sTaskExecWorkerStats. Task-pool and actor-pool operators both run_map_task.- On the driver,
MapOperator._task_done_callbackmerges the last block's snapshot of each successful task with the user'scombine. Failed and aborted tasks contribute nothing. - Built-ins (
sum,min,max) plus a custom form withzero,addandcombine. Thecombinecontract matchesAggregateFnV2: associative and commutative.
total = ray.data.Accumulator.sum()
def score(batch):
total.add(float(batch["loss"].sum()))
return batch
ray.data.read_parquet(...).map_batches(score).materialize()
print(total.value)
Prototype. A working prototype is on this branch: 5 files, about 230 added lines. It is not a PR. It has no unit tests or docs yet. I ran it on a Ray 3.0.0.dev0 nightly wheel with this checkout's python/ray/data:
- Works: task pool, fused operators, actor pool, sync generator UDFs, and actors with
max_concurrency=4. All gave exact sums. - Faults: a user exception retried in-task, a worker killed mid-task after blocks had already reached the driver, and an actor killed mid-task. Each fault was confirmed to fire, and each gave an exact sum.
- Tasks with no output rows (
flat_map,filter,map_batchesreturning empty) still emit one empty block, so their updates arrive. - Actor-pool UDFs run on a helper thread (
make_callable_class_single_threaded), where the thread-localTaskContextisn't set. The prototype passes the context to that thread. This is the one change outside the new feature's own code. - Not supported yet:
asyncUDFs, which run on the event-loop thread, fail with a clear error. - Existing tests for the actor pool, task pool and operators pass. The
test_stats.pyfailures I saw are identical on the unmodified baseline.
Known semantics. Re-running a lazy dataset adds to the value again until reset(). Lineage reconstruction can double-count, because a reconstructed task gets a new task_index. That could be fixed by deduplicating on lineage_task_id. I haven't tested reconstruction.
Questions
- Is reusing
CustomOpStatsacceptable, or would you prefer a different design? - Is passing
TaskContextto the helper thread inmake_callable_class_single_threadedacceptable? - Should accumulators be tied to the UDF through a driver-side registry keyed by UUID (no signature changes), or an explicit
accumulators=[...]argument? - Should values accumulate across executions until
reset(), or be scoped to one execution? Lazy datasets re-run on everyiter_batches(). - Where should this live, and what stability level? I'd suggest
ray.data.Accumulatorwith@PublicAPI(stability="alpha"). - Is "exact in the retry and restart cases I tested, at-least-once under lineage reconstruction" acceptable for a first release?
- Can a map transform ever finish without yielding any block while its UDF ran? I couldn't produce one. If it can happen, that task's updates would be missed.
Plan. (1) Core path for the task pool and actor pool, with tests and docs. (2) Fault-injection tests and a decision on async UDFs. (3) A batch-inference example in the docs.
I'd start once you confirm the direction. I'm using an AI assistant for research and drafting, and I'll review and test everything myself before opening any PR.