diff --git a/python/ray/data/_internal/block_batching/pinned_staging.py b/python/ray/data/_internal/block_batching/pinned_staging.py new file mode 100644 index 0000000000..8a3c285f02 --- /dev/null +++ b/python/ray/data/_internal/block_batching/pinned_staging.py @@ -0,0 +1,219 @@ +"""One-batch pinned-memory prefetch for synchronous map_batches GPU actors.""" + +from concurrent.futures import Future, ThreadPoolExecutor +from threading import RLock + + +class PinnedPrefetch: + """Stage concrete NumPy batches on one producer thread, in FIFO order. + + Only the consumer advances the upstream iterator. Each returned dictionary + owns fresh CUDA storage on actor-local cuda:0. There is at most one pending + batch in addition to the batch held by the consumer. + + staging_collate_fn, if supplied, receives owned, writable NumPy arrays on + the producer thread. It must return a nonempty dict of numeric NumPy arrays + or dense CPU tensors. It must not capture the actor/model, launch CUDA work, + or call this iterator's methods. + + Consume on one thread and use the returned tensors on that thread's + current CUDA stream. A UDF using additional streams must manage their + synchronization and record_stream calls itself. Call close() on early exit; + the map-task ExitStack and transform generator both do this. + """ + + def __init__(self, batches, staging_collate_fn=None): + if staging_collate_fn is not None and not callable(staging_collate_fn): + raise TypeError("staging_collate_fn must be callable or None") + + # Importing this module does not import or initialize torch. + import torch + + self._torch = torch + self._batches = iter(batches) + self._collate_fn = staging_collate_fn + self._device = torch.device("cuda", 0) + self._stream = torch.cuda.Stream(device=self._device) + self._pool = ThreadPoolExecutor( + max_workers=1, thread_name_prefix="ray-pinned-staging" + ) + self._pending = None + self._started = False + self._exhausted = False + self._closed = False + # Serialize close against next and other close calls. The producer + # never acquires this lock; joining it while holding the lock is safe. + self._lock = RLock() + + def __iter__(self): + return self + + def _submit_next(self): + """Called only by the consumer, with the iterator lock held.""" + if self._exhausted: + return None + try: + batch = next(self._batches) + except StopIteration: + self._exhausted = True + return None + except Exception as error: + self._exhausted = True + failed = Future() + failed.set_exception(error) + return failed + + try: + # Never pass the iterator or next(upstream) to the executor. + return self._pool.submit(self._stage, batch) + except Exception as error: + # Even submission failure during lookahead must preserve batch N. + self._exhausted = True + failed = Future() + failed.set_exception(error) + return failed + + @staticmethod + def _check_batch(batch): + if not isinstance(batch, dict) or not batch: + raise TypeError("Pinned staging requires a nonempty dict") + if not all(isinstance(key, str) for key in batch): + raise TypeError("Pinned staging requires string column names") + + @staticmethod + def _copy_array(value): + import numpy as np + + if not isinstance(value, np.ndarray) or value.dtype.kind not in "biufc": + raise TypeError("Pinned staging requires numeric or boolean arrays") + # An owned, writable, native-endian, C-contiguous copy also handles + # read-only object-store views and arrays with negative strides. + return np.array( + value, dtype=value.dtype.newbyteorder("="), order="C", copy=True + ) + + def _stage(self, batch): + import numpy as np + + torch = self._torch + host, device = {}, {} + with torch.cuda.device(self._device), torch.no_grad(): + try: + with torch.cuda.nvtx.range("ray::collate_pin"): + self._check_batch(batch) + if self._collate_fn is not None: + batch = self._collate_fn( + { + key: self._copy_array(value) + for key, value in batch.items() + } + ) + self._check_batch(batch) + + for key, value in batch.items(): + if isinstance(value, np.ndarray): + cpu = torch.from_numpy(self._copy_array(value)) + elif ( + isinstance(value, torch.Tensor) + and value.device.type == "cpu" + and value.layout == torch.strided + and not value.is_quantized + and not value.is_nested + ): + # pin_memory() may alias an already-pinned tensor. + # Start with fresh pageable storage even if the + # collator keeps or reuses its pinned output. + cpu = torch.empty( + tuple(value.shape), + dtype=value.dtype, + device="cpu", + pin_memory=False, + ) + cpu.copy_(value.detach()) + else: + raise TypeError( + f"Column {key!r}: expected a numeric NumPy " + "array or a dense, non-quantized CPU tensor" + ) + host[key] = cpu.pin_memory() + + with torch.cuda.stream(self._stream): + with torch.cuda.nvtx.range("ray::H2D"): + for key, pinned in host.items(): + device[key] = pinned.to( + self._device, non_blocking=True + ) + ready = torch.cuda.Event() + ready.record(self._stream) + + # The future completes only AFTER H2D completes. This wait is + # on the producer thread; compute for batch N can continue + # while the producer stages N+1. Keep all pinned sources alive. + ready.synchronize() + return device, ready + except BaseException as error: + # A later column's copy, event creation, or event recording + # can fail after earlier H2D work has already been issued. + # Drain before releasing any pinned source. + self._stream.synchronize() + if isinstance(error, StopIteration): + raise RuntimeError( + "staging_collate_fn raised StopIteration" + ) from error + raise + finally: + host.clear() + + def __next__(self): + with self._lock: + if self._closed: + raise StopIteration + try: + if not self._started: + self._started = True + self._pending = self._submit_next() + if self._pending is None: + self.close() + raise StopIteration + + # result() waits for the producer's ready.synchronize(). + device, ready = self._pending.result() + self._pending = None + stream = self._torch.cuda.current_stream(self._device) + stream.wait_event(ready) + for value in device.values(): + value.record_stream(stream) + + # Start N+1 before handing N to the UDF. An upstream exception + # is stored in a Future and raised on the next consumption. + self._pending = self._submit_next() + return device + except BaseException: + self.close() + raise + + def close(self): + """Join staging, drain issued H2D, and release unconsumed resources. + + Idempotent, including calls through both finally and ExitStack. Does + not advance upstream or surface errors from unconsumed lookahead. + Returned CUDA tensors remain owned by the UDF and are never overwritten. + """ + with self._lock: + if self._closed: + return + self._closed = True + try: + if self._pending is not None: + self._pending.cancel() + # Running jobs cannot be cancelled. _stage drains both normal + # and partially-issued H2D before returning or raising, so + # joining the producer also drains all issued copies. + self._pool.shutdown(wait=True, cancel_futures=True) + finally: + self._pending = None + self._batches = iter(()) + self._collate_fn = None + self._pool = None + self._stream = None + self._torch = None diff --git a/python/ray/data/_internal/compute.py b/python/ray/data/_internal/compute.py index d8eb354c0e..e120814bd4 100644 --- a/python/ray/data/_internal/compute.py +++ b/python/ray/data/_internal/compute.py @@ -116,6 +116,8 @@ class ActorPoolStrategy(ComputeStrategy): max_tasks_in_flight_per_actor: Optional[int] = None, max_concurrent_calls_per_actor: Optional[int] = None, enable_true_multi_threading: Optional[bool] = None, + pinned_staging: bool = False, + staging_collate_fn: Optional[Callable] = None, ): """Construct ActorPoolStrategy for a Dataset transform. @@ -137,6 +139,16 @@ class ActorPoolStrategy(ComputeStrategy): than 1 UDF runs per actor. Otherwise, respects the `max_concurrent_calls_per_actor` argument. By default, this flag is `None`, which gets translated to `False`. For more details, see the `ActorPoolStrategy` class docstring. + pinned_staging: Experimental map_batches-only CUDA staging. Defaults + to False. Requires num_gpus=1, a positive integer batch_size, + batch_format="numpy", zero_copy_batch=False and a synchronous + UDF. Sets actor call concurrency to 1 and disables fusion. + The UDF receives a dict of CUDA tensors on local cuda:0 instead + of NumPy arrays. Prefetches one batch within each actor task. + staging_collate_fn: Optional deterministic CPU-only callable, + executed on the staging thread with an owned NumPy batch. + Return a nonempty dict of dense CPU tensors or numeric arrays. + Must not capture the actor/model or launch CUDA work. """ if size is not None: if size < 1: @@ -172,6 +184,19 @@ class ActorPoolStrategy(ComputeStrategy): max_concurrent_calls_per_actor, ) + if staging_collate_fn is not None and ( + not pinned_staging or not callable(staging_collate_fn) + ): + raise ValueError("staging_collate_fn requires pinned_staging=True") + if pinned_staging: + if enable_true_multi_threading or max_concurrent_calls_per_actor not in ( + None, 1 + ): + raise ValueError("pinned_staging requires one synchronous actor call") + max_concurrent_calls_per_actor = 1 + self.pinned_staging = pinned_staging + self.staging_collate_fn = staging_collate_fn + self.min_size = min_size or 1 self.max_size = max_size or float("inf") @@ -213,6 +238,10 @@ class ActorPoolStrategy(ComputeStrategy): and self.max_size == other.max_size and self.initial_size == other.initial_size and self.enable_true_multi_threading == other.enable_true_multi_threading + and getattr(self, "pinned_staging", False) + == getattr(other, "pinned_staging", False) + and getattr(self, "staging_collate_fn", None) + == getattr(other, "staging_collate_fn", None) and self.max_tasks_in_flight_per_actor == other.max_tasks_in_flight_per_actor and self.max_concurrent_calls_per_actor @@ -226,6 +255,7 @@ class ActorPoolStrategy(ComputeStrategy): f"initial_size={self.initial_size}, " f"max_tasks_in_flight_per_actor={self.max_tasks_in_flight_per_actor}, " f"max_concurrent_calls_per_actor={self.max_concurrent_calls_per_actor}, " + f"pinned_staging={getattr(self, 'pinned_staging', False)}, " f"num_workers={self.num_workers}, " f"enable_true_multi_threading={self.enable_true_multi_threading}, " f"ready_to_total_workers_ratio={self.ready_to_total_workers_ratio})" diff --git a/python/ray/data/_internal/execution/interfaces/task_context.py b/python/ray/data/_internal/execution/interfaces/task_context.py index 35ce6506ea..1701595883 100644 --- a/python/ray/data/_internal/execution/interfaces/task_context.py +++ b/python/ray/data/_internal/execution/interfaces/task_context.py @@ -47,6 +47,11 @@ class TaskContext: # Override of the target max-block-size for the task target_max_block_size_override: Optional[int] = None + # Worker-local cleanup, installed by _map_task (never sent from the driver). + _pinned_staging_cleanup: Optional[contextlib.ExitStack] = field( + default=None, init=False, repr=False, compare=False + ) + # Additional keyword arguments passed to the task. kwargs: Dict[str, Any] = field(default_factory=dict) diff --git a/python/ray/data/_internal/execution/operators/map_operator.py b/python/ray/data/_internal/execution/operators/map_operator.py index 818c62cf31..dcd43c335c 100644 --- a/python/ray/data/_internal/execution/operators/map_operator.py +++ b/python/ray/data/_internal/execution/operators/map_operator.py @@ -6,6 +6,7 @@ import logging import math import time from abc import ABC, abstractmethod +from contextlib import ExitStack from dataclasses import replace from typing import ( TYPE_CHECKING, @@ -818,7 +819,12 @@ def _map_task( ctx.kwargs.update(kwargs) - with DataContext.current(data_context), TaskContext.current(ctx): + with ( + DataContext.current(data_context), + TaskContext.current(ctx), + ExitStack() as staging_cleanup, + ): + ctx._pinned_staging_cleanup = staging_cleanup map_transformer.override_target_max_block_size( ctx.target_max_block_size_override ) @@ -843,6 +849,9 @@ def _map_task( udf_time_scope = UDFTimeScope() def transform_iter_factory(): + # Close the previous attempt before creating a fresh producer. + # The outer ExitStack also handles cancellation/GeneratorExit. + staging_cleanup.close() # Clear any per-task custom stats before each attempt (the reporter # is reused across retries of this task), so a prior attempt's stats # can't leak into this one. A producing transform repopulates it diff --git a/python/ray/data/_internal/planner/plan_udf_map_op.py b/python/ray/data/_internal/planner/plan_udf_map_op.py index 8d0af2b4d4..9d5e740a78 100644 --- a/python/ray/data/_internal/planner/plan_udf_map_op.py +++ b/python/ray/data/_internal/planner/plan_udf_map_op.py @@ -297,6 +297,32 @@ def plan_udf_map_op( ) compute = get_compute(op.compute) + pinned_staging = getattr(compute, "pinned_staging", False) + if pinned_staging: + from ray.data._internal.utils.torch_inference import ( + _BaseTorchInferenceUDFWrapper, + ) + + user_fn = op.fn.__call__ if isinstance(op.fn, CallableClass) else op.fn + if ( + not isinstance(op, MapBatches) + or op.zero_copy_batch + or op.batch_format != "numpy" + or type(op.batch_size) is not int + or op.batch_size < 1 + or op.ray_remote_args.get("num_gpus") != 1 + or op.ray_remote_args_fn is not None + or _is_async_udf(user_fn) + or ( + isinstance(op.fn, type) + and issubclass(op.fn, _BaseTorchInferenceUDFWrapper) + ) + ): + raise ValueError( + "pinned_staging requires synchronous map_batches, " + "zero_copy_batch=False, batch_format='numpy', integer batch_size, " + "num_gpus=1, and no TorchInference wrapper or ray_remote_args_fn" + ) udf_is_callable_class = isinstance(op.fn, CallableClass) fn, init_fn = _get_udf( op.fn, @@ -309,10 +335,15 @@ def plan_udf_map_op( if isinstance(op, MapBatches): transform_fn = BatchMapTransformFn( - _generate_transform_fn_for_map_batches(fn), + _generate_transform_fn_for_map_batches( + fn, pinned_staging=pinned_staging, + staging_collate_fn=getattr(compute, "staging_collate_fn", None), + ), batch_size=op.batch_size, batch_format=op.batch_format, - zero_copy_batch=op.zero_copy_batch, + # Private CPU views are never given to the UDF. Staging makes + # owned pinned/device copies, and copies collator input if needed. + zero_copy_batch=True if pinned_staging else op.zero_copy_batch, is_udf=True, output_block_size_option=output_block_size_option, ) @@ -343,6 +374,7 @@ def plan_udf_map_op( ray_remote_args_fn=op.ray_remote_args_fn, ray_remote_args=op.ray_remote_args, per_block_limit=op.per_block_limit, + supports_fusion=not pinned_staging, ) @@ -376,6 +408,9 @@ def _get_udf( not is_async_udf and isinstance(compute, ActorPoolStrategy) and not compute.enable_true_multi_threading + # Staging fixes actor call concurrency at one; keep the UDF on + # the thread/stream where staged inputs are handed off. + and not getattr(compute, "pinned_staging", False) ): # NOTE: By default Actor-based UDFs are restricted to run within a # single-thread (when enable_true_multi_threading=False). @@ -621,9 +656,25 @@ class _TransformingBatchIterator(Iterator[DataBatch]): def _generate_transform_fn_for_map_batches( fn: UserDefinedFunction, + *, + pinned_staging: bool = False, + staging_collate_fn: Optional[Callable] = None, ) -> MapTransformCallable[DataBatch, DataBatch]: - if _is_async_udf(fn): + if pinned_staging: + def transform_fn(batches, ctx): + from ray.data._internal.block_batching.pinned_staging import PinnedPrefetch + + if ctx._pinned_staging_cleanup is None: + raise RuntimeError("Pinned staging requires a map task cleanup scope") + staged = PinnedPrefetch(batches, staging_collate_fn) + ctx._pinned_staging_cleanup.callback(staged.close) + try: + yield from _TransformingBatchIterator(staged, fn) + finally: + staged.close() + + elif _is_async_udf(fn): transform_fn = _generate_transform_fn_for_async_map( fn, _validate_batch_output, diff --git a/python/ray/data/tests/block_batching/test_pinned_staging.py b/python/ray/data/tests/block_batching/test_pinned_staging.py new file mode 100644 index 0000000000..4718d0ffb6 --- /dev/null +++ b/python/ray/data/tests/block_batching/test_pinned_staging.py @@ -0,0 +1,133 @@ +import sys +import threading +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from types import SimpleNamespace + +import pytest + +from ray.data._internal.block_batching.pinned_staging import PinnedPrefetch + + +@pytest.fixture +def fake_prefetch(monkeypatch): + stream = SimpleNamespace(wait_event=lambda event: None) + torch = SimpleNamespace( + device=lambda *args: "cuda:0", + cuda=SimpleNamespace( + Stream=lambda **kwargs: stream, + current_stream=lambda device: stream, + ), + ) + monkeypatch.setitem(sys.modules, "torch", torch) + + class Prefetch(PinnedPrefetch): + def _stage(self, batch): + return { + "x": SimpleNamespace(value=batch, record_stream=lambda stream: None) + }, None + + return Prefetch + + +def test_fifo_thread_boundary_and_lookahead(fake_prefetch): + owner = threading.get_ident() + produced = [] + second_started = threading.Event() + + class Prefetch(fake_prefetch): + def _stage(self, batch): + assert threading.get_ident() != owner + produced.append(batch) + if batch == 1: + second_started.set() + return super()._stage(batch) + + def upstream(): + for i in range(4): + assert threading.get_ident() == owner + yield i + + p = Prefetch(upstream()) + try: + assert next(p)["x"].value == 0 + # N+1 staging is running while the consumer still owns N. + assert second_started.wait(3) + assert [b["x"].value for b in p] == [1, 2, 3] + assert produced == [0, 1, 2, 3] + finally: + p.close() + + +def test_lookahead_error_preserves_good_batch(fake_prefetch): + def upstream(): + yield 7 + raise ValueError("upstream failed") + + p = fake_prefetch(upstream()) + assert next(p)["x"].value == 7 + with pytest.raises(ValueError, match="upstream failed"): + next(p) + assert p._closed + + +def test_cleanup_joins_running_producer_before_retry(fake_prefetch): + started, release, drained = (threading.Event() for _ in range(3)) + + class Prefetch(fake_prefetch): + def _stage(self, batch): + if batch == 1: + started.set() + assert release.wait(3) + drained.set() + return super()._stage(batch) + + p = Prefetch(iter([0, 1, 2])) + cleanup = ExitStack() + cleanup.callback(p.close) + assert next(p)["x"].value == 0 + assert started.wait(3) + with ThreadPoolExecutor(max_workers=1) as closer: + closing = closer.submit(cleanup.close) + try: + assert not drained.is_set() + assert not closing.done() + finally: + release.set() + closing.result(timeout=3) + assert drained.is_set() + assert p._closed and p._pending is None + retry = fake_prefetch(iter([0, 1, 2])) + assert [b["x"].value for b in retry] == [0, 1, 2] + + +def test_cuda_owned_buffers_mutating_collator_and_tail(): + import numpy as np + + torch = pytest.importorskip("torch") + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + + source = np.arange(8, dtype=np.float32).reshape(4, 2) + source.flags.writeable = False + + def collate(batch): + batch["x"] += 1 + return batch + + compute = torch.cuda.Stream() + retained = [] + with torch.cuda.stream(compute): + p = PinnedPrefetch(iter([{"x": source}, {"x": source[:1]}]), collate) + try: + for batch in p: + retained.append(batch["x"]) + # Exercise mutation outside torch.inference_mode. + batch["x"].add_(2) + finally: + p.close() + compute.synchronize() + np.testing.assert_array_equal(source, np.arange(8).reshape(4, 2)) + np.testing.assert_array_equal(retained[0].cpu().numpy(), source + 3) + np.testing.assert_array_equal(retained[1].cpu().numpy(), source[:1] + 3) + assert retained[0].data_ptr() != retained[1].data_ptr()