Repository navigation
[Data] Stop the block prefetcher when iteration ends early - #67355
iamjustinhsu merged 1 commit into
Conversation
Consumers that stop iter_batches before the stream ends (for example Lightning's limit_train_batches) never stopped the WaitBlockPrefetcher. Its parked thread kept the last prefetched block refs alive, pinning spilled objects until the disk filled. - Stop the prefetcher in a finally, on the consumer's thread. - Stop it in prefetch_batches_locally's finally as well. - Start no prefetcher thread when prefetch_batches <= 0. - Drop fetched refs before the prefetcher thread parks. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Prasad Palkar <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request improves resource management and prevents memory leaks in Ray's block batching prefetcher by ensuring prefetchers are stopped and block references are cleared when iteration ends early or fails. It also introduces a DisabledBlockPrefetcher to avoid starting threads when prefetching is disabled. The review feedback highlights two critical issues: first, after_epoch_end() should be moved to the finally block in _iter_batches to prevent resource accounting leaks when iteration is interrupted; second, a reference cycle leak in WaitBlockPrefetcher prevents garbage collection of the prefetcher, which can be resolved by using a weak reference for the background thread target.
| finally: | ||
| # A consumer that stops early (``break``, ``close()``, or dropping | ||
| # the iterator) leaves the pipeline suspended in its background | ||
| # thread, where the prefetcher would otherwise only be stopped if | ||
| # that thread's generators are garbage collected. A prefetcher | ||
| # that isn't stopped keeps its thread, and the blocks it last | ||
| # prefetched, alive for the life of the process. Stop it here, on | ||
| # the consumer's thread, after signaling the pipeline to stop. | ||
| batch_iter.close() | ||
| self._prefetcher.stop() | ||
|
|
||
| self.after_epoch_end() |
There was a problem hiding this comment.
If the consumer stops early or an exception is raised, after_epoch_end() is never called. This means self._prefetch_bytes_callback(0) is never invoked, which can lead to a resource accounting leak in the executor's resource manager (as the manager will still believe the last reported prefetched bytes are active). Moving self.after_epoch_end() into the finally block ensures that the resource manager is always notified of 0 prefetched bytes when the iterator is terminated or closed.
| finally: | |
| # A consumer that stops early (``break``, ``close()``, or dropping | |
| # the iterator) leaves the pipeline suspended in its background | |
| # thread, where the prefetcher would otherwise only be stopped if | |
| # that thread's generators are garbage collected. A prefetcher | |
| # that isn't stopped keeps its thread, and the blocks it last | |
| # prefetched, alive for the life of the process. Stop it here, on | |
| # the consumer's thread, after signaling the pipeline to stop. | |
| batch_iter.close() | |
| self._prefetcher.stop() | |
| self.after_epoch_end() | |
| finally: | |
| # A consumer that stops early (``break``, ``close()``, or dropping | |
| # the iterator) leaves the pipeline suspended in its background | |
| # thread, where the prefetcher would otherwise only be stopped if | |
| # that thread's generators are garbage collected. A prefetcher | |
| # that isn't stopped keeps its thread, and the blocks it last | |
| # prefetched, alive for the life of the process. Stop it here, on | |
| # the consumer's thread, after signaling the pipeline to stop. | |
| batch_iter.close() | |
| self._prefetcher.stop() | |
| self.after_epoch_end() |
| finally: | ||
| # Drop the references before parking, so an idle prefetcher | ||
| # doesn't keep the blocks it last fetched alive. | ||
| blocks_to_fetch = [] |
There was a problem hiding this comment.
There is a classic catch-22 reference cycle leak in WaitBlockPrefetcher. The thread is started with target=self._run, which is a bound method holding a strong reference to self. Because the thread is kept alive in threading._active while running, it acts as a GC root, preventing WaitBlockPrefetcher from ever being garbage collected. Consequently, del is never called, and the thread is never stopped, leading to a permanent leak if the iterator is discarded without being iterated or if an exception is raised before iteration starts.
To fix this, we can use a weak reference to self for the thread target, and implement the run loop as a static method that dereferences the weakref. For example:
class WaitBlockPrefetcher(BlockPrefetcher):
def __init__(self):
self._blocks = []
self._stopped = False
self._condition = threading.Condition()
self._thread = threading.Thread(
target=self._run_prefetcher,
args=(weakref.ref(self),),
name="Prefetcher",
daemon=True,
)
self._thread.start()
@staticmethod
def _run_prefetcher(weak_self):
self = weak_self()
if self is None:
return
condition = self._condition
while True:
try:
with condition:
self = weak_self()
if self is None or self._stopped:
break
if len(self._blocks) == 0:
self = None
condition.wait()
self = weak_self()
if self is None or self._stopped:
break
blocks_to_fetch, self._blocks = self._blocks[:], []
if len(blocks_to_fetch) > 0:
ray.wait(blocks_to_fetch, num_returns=1, timeout=0, fetch_local=True)
except Exception:
logger.exception("Error in prefetcher thread.")
finally:
blocks_to_fetch = []
self = None
Jadiouo
left a comment
There was a problem hiding this comment.
Verified against base 3c56135 and head 1faf3e1 (Python 3.13, CPU only).
- With public APIs (
ds.iter_batches(batch_size=100, prefetch_batches=k), breaking after 4 batches, 24 epochs), base leaves 24 livePrefetcherthreads for bothprefetch_batches=2and0; head leaves none. Base also leaks one idle thread per full iteration withprefetch_batches=0; head doesn't. - An exception in the loop,
iter_torch_batches,streaming_splitwith one consumer stopping early, andnext(it); del italso leak on base and not on head. Re-iterating after a break works. - The 9 new tests fail on base and pass on head;
block_batching/is 145 passed. I didn't runtest_split.py.
On gemini's points: after_epoch_end() is already skipped on early exit on master, and moving it into the finally would also call CheckpointingBatchIterator's end_epoch() for a partial epoch, which advances the epoch index. The cycle no longer matters once stop() runs in the finally; the prefetcher is collected after a break.
LGTM.
…strings on iteration APIs (#67486) ## Summary Corrects the `prefetch_batches` and `local_shuffle_buffer_size` argument docstrings that are copied across the `Dataset` and `DataIterator` iteration APIs, so they describe what `BatchIterator` and `ShufflingBatcher` actually do. This is a docstring-only change. Behavior is unchanged. This came up while reviewing #67454, which documents the iteration pipeline on the Ray Data internals page. The API reference pages that section links to contradicted its diagram. ## Before ### `prefetch_batches` The shared text said: > The number of batches to fetch ahead of the current batch to fetch. If set to greater than 0, a separate threadpool will be used to fetch the objects to the local node, format the batches, and apply the collate_fn. Defaults to 1. That doesn't match `python/ray/data/_internal/block_batching/iter_batches.py`: - Iteration always runs in a background thread. `_iter_batches` wraps the pipeline in `iter_threaded(...)` whatever the value of `prefetch_batches`. - The format and collate pool has `min(RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS, prefetch_batches)` workers, and that environment variable defaults to 4. Setting `prefetch_batches` above 4 fetches further ahead but adds no threads, and the docstring didn't say so. - With `prefetch_batches=0`, there's no pool. `prefetch_batches_locally` yields block refs without prefetching, and format and collate run inline. - `iter_batches`, `iter_tf_batches`, `to_tf`, and `to_torch` don't accept a `collate_fn`, but their docstrings mentioned applying one. - The first sentence repeated "to fetch". `iter_jax_batches` had a different one-line version. ### `local_shuffle_buffer_size` The docstrings disagreed with each other and with `ShufflingBatcher` in `python/ray/data/_internal/batcher.py`: - The `iter_torch_batches`, `iter_tf_batches`, `to_torch`, and `to_tf` docstrings said the buffer size "must be greater than or equal to `batch_size`." The code doesn't reject a smaller value. It rounds it up to `batch_size`. - `ShufflingBatcher` raises `ValueError` when `batch_size` is `None`. Only some docstrings said `batch_size` is required, and `iter_batches`, which accepts `batch_size=None`, didn't. - `DataIterator.iter_jax_batches` had a one-line version, "Minimum rows for local in-memory shuffle." - None of them stated the trade-off that `ShufflingBatcher`'s own docstring gives: a larger buffer is more random but adds latency to the first batch. ## After ### `prefetch_batches` Every `prefetch_batches` docstring now uses the same text. Methods that accept `collate_fn` (`iter_torch_batches`, `iter_jax_batches`) mention collation, and the others don't: > The number of batches to fetch ahead of the current batch. Ray Data prepares batches in background threads while your code consumes the current one. If greater than 0, a thread pool formats the batches. The pool has `prefetch_batches` threads, up to a limit of 4. To change the limit, set the `RAY_DATA_MAX_FORMAT_THREADPOOL_NUM_WORKERS` environment variable. If 0, Ray Data doesn't prefetch blocks and formats each batch without the thread pool. Defaults to 1. ### `local_shuffle_buffer_size` Every docstring now uses the same text: > If not `None`, Ray Data randomly shuffles the data using a local in-memory shuffle buffer, and this value serves as the minimum number of rows that must be in the buffer to yield a batch. When there are no more rows to add to the buffer, Ray Data drains the remaining rows. A larger buffer makes the shuffle more random but might increase the latency to the first batch. If this value is smaller than `batch_size`, Ray Data rounds it up to `batch_size`. Local shuffling raises a `ValueError` if `batch_size` is `None`. I kept the "minimum number of rows" sentence's meaning as it was. It's an approximation of the compaction watermarks in `ShufflingBatcher.has_batch()`, and I've asked in a comment below whether you want it more precise. Updated methods, for both arguments: - `DataIterator`: `iter_batches`, `iter_torch_batches`, `iter_tf_batches`, `iter_jax_batches`, `to_torch`, and `to_tf`. - `Dataset`: `iter_batches`, `iter_torch_batches`, `iter_tf_batches`, `iter_jax_batches`, and `to_tf`. ## Subsystems API (docstrings only) ## Not a duplicate I searched open PRs for `prefetch_batches` and iterator docstring changes. #67355 touches `iter_batches.py` and `util.py` to stop the block prefetcher early, but it doesn't change these docstrings, the thread-pool sizing, or `ShufflingBatcher`. ## Testing - `pre-commit run --files python/ray/data/iterator.py python/ray/data/dataset.py` passes, including ruff, black, pydoclint, and the Ray docstyle check. - I checked each claim against `iter_batches.py` (`_format_batches`, `_iter_batches`, `prefetch_batches_locally`), `util.py` (`iter_threaded`), and `batcher.py` (`ShufflingBatcher.__init__` and `has_batch`) on master. - I didn't run a local Sphinx build. The change is plain prose plus inline literals. The `docstring-only` label is applied to skip the heavy Ray Data test suites. I wrote this with AI assistance (Claude Code). I reviewed every changed line and can defend the change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
ayushk7102
left a comment
There was a problem hiding this comment.
LGTM, thanks for the fix. Left one comment
| assert batch_iterator._prefetcher._stopped | ||
| assert _new_prefetcher_threads_still_alive(baseline) == [] |
There was a problem hiding this comment.
Nit: ideally I don't think we should be asserting private variables. It makes sense here though but we can consider exposing this if required
Why are these changes needed?
When a consumer stops
iter_batches/iter_torch_batchesbefore the stream ends (for example PyTorch Lightning'slimit_train_batcheswithstreaming_split), theWaitBlockPrefetcheris never stopped:prefetch_batches_locallycallsprefetcher.stop()only after its loop, soGeneratorExitskips it. Theprefetch_batches=0path returns before reaching it.self._run, which keeps the prefetcher alive, so__del__never runs. The parked thread still holdsblocks_to_fetch.So every abandoned epoch leaks a thread pinning its last prefetch window. Under memory pressure, those blocks are spilled into fused files that can't be deleted while any member is referenced, and long training jobs eventually fill the spill disk. With
prefetch_batches=0, every iterator also leaks an idle thread.What this PR does
BatchIterator._iter_batchescloses the pipeline and stops the prefetcher in afinally, on the consumer's thread.prefetch_batches_locallyalso stops it in afinally, covering theprefetch_batches <= 0path.prefetch_batches <= 0uses aDisabledBlockPrefetcherthat starts no thread.WaitBlockPrefetcher._rundrops fetched refs before parking.Testing
9 new tests in
block_batching/test_iter_batches.pyandtest_util.py: early close, upstream error, consumer stopping early, no thread without prefetching, idle prefetcher releasing refs, andstreaming_splitconsumers stopping early. All failed before the fix and pass after it.Run against the Ray nightly wheel with this branch's
ray/data:A standalone repro (24 epochs, each breaking after 4 batches) goes from 18 leaked threads / 36 pinned refs to 0 / 0.
Duplicate check
No open PR or issue covers this. I searched open PRs and issues for
prefetcher,WaitBlockPrefetcher,prefetch_batches_locallyand "iter_batches leak".AI assistance (Claude Code) was used. I reviewed every changed line and ran the tests above.