File size: 24,572 Bytes
fa05bf1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | 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()
|