ray icon indicating copy to clipboard operation
ray copied to clipboard

[Data] Implement Spark-like accumulators in Ray Data

Open marwan116 opened this issue 2 years ago • 4 comments

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_batches to perform a local aggregation along with a ds.aggregate call. This is not as flexible of a solution especially when:
    • A user wants to aggregate multiple evaluation metrics - i.e. a single ds.aggregate call is not enough.
    • Dealing with very large datasets given ds.aggregate requires materializing all inputs.

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()

marwan116 avatar Oct 16 '24 18:10 marwan116

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.

wingkitlee0 avatar Oct 26 '24 18:10 wingkitlee0

Hey @marwan116 @alexeykudinkin any update on this one?

jcotant1 avatar Nov 04 '24 19:11 jcotant1

No updates this is in the backlog

alexeykudinkin avatar Nov 04 '24 20:11 alexeykudinkin

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's TaskContext. There is no RPC. The partial is cleared at the start of each task attempt, like CustomOpStatsReporter.
  • _map_task snapshots the partials, cumulatively, into a new CustomOpStats subclass on each block's TaskExecWorkerStats. Task-pool and actor-pool operators both run _map_task.
  • On the driver, MapOperator._task_done_callback merges the last block's snapshot of each successful task with the user's combine. Failed and aborted tasks contribute nothing.
  • Built-ins (sum, min, max) plus a custom form with zero, add and combine. The combine contract matches AggregateFnV2: 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_batches returning 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-local TaskContext isn'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: async UDFs, 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.py failures 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

  1. Is reusing CustomOpStats acceptable, or would you prefer a different design?
  2. Is passing TaskContext to the helper thread in make_callable_class_single_threaded acceptable?
  3. Should accumulators be tied to the UDF through a driver-side registry keyed by UUID (no signature changes), or an explicit accumulators=[...] argument?
  4. Should values accumulate across executions until reset(), or be scoped to one execution? Lazy datasets re-run on every iter_batches().
  5. Where should this live, and what stability level? I'd suggest ray.data.Accumulator with @PublicAPI(stability="alpha").
  6. Is "exact in the retry and restart cases I tested, at-least-once under lineage reconstruction" acceptable for a first release?
  7. 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.

gamidirohan avatar Nov 19 '26 09:11 gamidirohan