Repository navigation
[data][train] Mid-epoch resumption (2/n): Add save/load APIs on the training worker side - #66562
Conversation
Signed-off-by: Justin Yu <[email protected]>
Signed-off-by: Justin Yu <[email protected]>
7dfc2d1 to
ab3d0dc
Compare
Signed-off-by: Justin Yu <[email protected]>
ab3d0dc to
2f9999c
Compare
Signed-off-by: Justin Yu <[email protected]>
2f9999c to
a58a022
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces a dataset checkpointing mechanism for training ingest in Ray Train V2, allowing the state of a data iterator to be saved and restored mid-epoch. It implements an asynchronous checkpointer (RowIDBasedDataIteratorCheckpointer) that records yielded row IDs and flushes them to Parquet files, along with integration into the batch iterator and training callbacks. The feedback focuses on critical improvements to the checkpointer's background thread: resolving a strong reference cycle that causes memory leaks, capturing thread-local DataContext settings on the main thread to prevent context loss in the background thread, avoiding layering violations by removing imports from ray.train inside ray.data, and raising user-friendly exceptions instead of raw assertions.
| from ray.data.context import DataContext | ||
| from ray.data.datasource import PartitionStyle, PathPartitionFilter | ||
|
|
||
| logger = logging.getLogger(__name__) |
There was a problem hiding this comment.
| self._checkpoint_config = checkpoint_config | ||
| self._id_column = checkpoint_config.id_column |
There was a problem hiding this comment.
DataContext is stored in thread-local storage. Accessing DataContext.get_current() in the background flush thread will return a default context, losing any custom configurations (such as custom retried_io_errors). Capture retried_io_errors on the main thread during initialization.
self._checkpoint_config = checkpoint_config
self._id_column = checkpoint_config.id_column
self._retried_io_errors = DataContext.get_current().retried_io_errors| self._flush_thread = threading.Thread( | ||
| target=self._process_row_ids_from_queue, | ||
| daemon=True, | ||
| name="DataIteratorCheckpointer-flush", | ||
| ) |
There was a problem hiding this comment.
The background thread target self._process_row_ids_from_queue is a bound method of self, which holds a strong reference to self. Since the thread is registered globally and runs indefinitely, this creates a strong reference cycle that prevents the checkpointer from ever being garbage collected. Use a static helper method with a weak reference to self to avoid this leak.
| self._flush_thread = threading.Thread( | |
| target=self._process_row_ids_from_queue, | |
| daemon=True, | |
| name="DataIteratorCheckpointer-flush", | |
| ) | |
| import weakref | |
| self._flush_thread = threading.Thread( | |
| target=self._process_row_ids_from_queue_helper, | |
| args=( | |
| weakref.ref(self), | |
| self._row_ids_staging_queue, | |
| self._flush_completed_event, | |
| _SHUTDOWN_SENTINEL, | |
| ), | |
| daemon=True, | |
| name="DataIteratorCheckpointer-flush", | |
| ) |
| call_with_retry( | ||
| _write, | ||
| description=f"Write checkpoint file: {checkpoint_path}", | ||
| match=DataContext.get_current().retried_io_errors, | ||
| ) |
There was a problem hiding this comment.
Use the captured _retried_io_errors from the main thread instead of calling DataContext.get_current() in the background thread to ensure thread-local settings are preserved.
| call_with_retry( | |
| _write, | |
| description=f"Write checkpoint file: {checkpoint_path}", | |
| match=DataContext.get_current().retried_io_errors, | |
| ) | |
| call_with_retry( | |
| _write, | |
| description=f"Write checkpoint file: {checkpoint_path}", | |
| match=self._retried_io_errors, | |
| ) |
| def _process_row_ids_from_queue(self): | ||
| """Process recorded row IDs from the staging queue. | ||
|
|
||
| This method should run in a background thread and is responsible for | ||
| flushing staged row IDs to a checkpoint file when reaching the target | ||
| file-size or when the main thread requests a forced flush. | ||
| """ | ||
| staged_row_ids_size_bytes = 0 | ||
| staged_row_id_batches: List[pa.Array] = [] | ||
|
|
||
| try: | ||
| while True: | ||
| row_ids = self._row_ids_staging_queue.get() | ||
| if row_ids is None: | ||
| # Sentinel value `None` indicates that we should force flush any | ||
| # staged row IDs. | ||
| if staged_row_id_batches: | ||
| self._flush_row_ids(staged_row_id_batches) | ||
| staged_row_ids_size_bytes = 0 | ||
| staged_row_id_batches = [] | ||
| # Notify the main thread that the flush is complete. | ||
| self._flush_completed_event.set() | ||
| continue | ||
|
|
||
| row_ids_accessor = BlockAccessor.for_block(row_ids) | ||
| row_ids_array: pa.ChunkedArray = row_ids_accessor.to_arrow().column( | ||
| self._id_column | ||
| ) | ||
| # Create an independent copy of the row IDs array to allow | ||
| # garbage collection of the original table. | ||
| # Without this copy, the original table would be kept | ||
| # in memory until all batches of row IDs pointing to it are flushed. | ||
| row_ids_array: pa.Array = deepcopy_array(row_ids_array) | ||
| size_bytes = row_ids_accessor.size_bytes() | ||
|
|
||
| staged_row_ids_size_bytes += size_bytes | ||
| staged_row_id_batches.append(row_ids_array) | ||
| if staged_row_ids_size_bytes >= self.TARGET_CHECKPOINT_SIZE_BYTES: | ||
| self._flush_row_ids(staged_row_id_batches) | ||
| staged_row_ids_size_bytes = 0 | ||
| staged_row_id_batches = [] | ||
| except Exception as e: | ||
| logger.exception("Internal error in background flush thread:") | ||
| self._flush_exception = e | ||
| self._flush_completed_event.set() | ||
| raise |
There was a problem hiding this comment.
Refactor the background thread loop into a static helper method that accepts a weak reference to self and handles the shutdown sentinel to prevent memory and thread leaks.
@staticmethod
def _process_row_ids_from_queue_helper(
weak_self,
queue: Queue,
flush_completed_event: threading.Event,
shutdown_sentinel: Any,
):
staged_row_ids_size_bytes = 0
staged_row_id_batches: List[pa.Array] = []
try:
while True:
row_ids = queue.get()
if row_ids is shutdown_sentinel:
break
s = weak_self()
if s is None:
break
if row_ids is None:
# Sentinel value `None` indicates that we should force flush any
# staged row IDs.
if staged_row_id_batches:
s._flush_row_ids(staged_row_id_batches)
staged_row_ids_size_bytes = 0
staged_row_id_batches = []
# Notify the main thread that the flush is complete.
flush_completed_event.set()
continue
row_ids_accessor = BlockAccessor.for_block(row_ids)
row_ids_array: pa.ChunkedArray = row_ids_accessor.to_arrow().column(
s._id_column
)
# Create an independent copy of the row IDs array to allow
# garbage collection of the original table.
# Without this copy, the original table would be kept
# in memory until all batches of row IDs pointing to it are flushed.
row_ids_array: pa.Array = deepcopy_array(row_ids_array)
size_bytes = row_ids_accessor.size_bytes()
staged_row_ids_size_bytes += size_bytes
staged_row_id_batches.append(row_ids_array)
if staged_row_ids_size_bytes >= s.TARGET_CHECKPOINT_SIZE_BYTES:
s._flush_row_ids(staged_row_id_batches)
staged_row_ids_size_bytes = 0
staged_row_id_batches = []
except Exception as e:
logger.exception("Internal error in background flush thread:")
s = weak_self()
if s is not None:
s._flush_exception = e
flush_completed_event.set()
raise| def __del__(self): | ||
| if self._delete_threadpool: | ||
| self._delete_threadpool.shutdown(wait=True) |
There was a problem hiding this comment.
Ensure the background flush thread is cleanly shut down when the checkpointer is garbage collected by putting the shutdown sentinel into the queue.
| def __del__(self): | |
| if self._delete_threadpool: | |
| self._delete_threadpool.shutdown(wait=True) | |
| def __del__(self): | |
| if hasattr(self, "_row_ids_staging_queue") and self._row_ids_staging_queue is not None: | |
| self._row_ids_staging_queue.put(_SHUTDOWN_SENTINEL) | |
| if hasattr(self, "_delete_threadpool") and self._delete_threadpool is not None: | |
| self._delete_threadpool.shutdown(wait=True) |
…t set Signed-off-by: Justin Yu <[email protected]>
a58a022 to
c348e59
Compare
c348e59 to
009ee6c
Compare
Signed-off-by: Justin Yu <[email protected]>
009ee6c to
a8249c7
Compare
Signed-off-by: Justin Yu <[email protected]>
a8249c7 to
148225d
Compare
Signed-off-by: Justin Yu <[email protected]>
a688457 to
fdca178
Compare
…ator-checkpoint Signed-off-by: Justin Yu <[email protected]>
Signed-off-by: Justin Yu <[email protected]>
Signed-off-by: Justin Yu <[email protected]>
Signed-off-by: Justin Yu <[email protected]>
fdca178 to
8c4ef0e
Compare
…API docs check Signed-off-by: Justin Yu <[email protected]>
Signed-off-by: Justin Yu <[email protected]>
8c4ef0e to
3861a06
Compare
…-epoch-resumption Signed-off-by: Justin Yu <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 5252da1. Configure here.
| self._build_restoration_checkpoint_config( | ||
| self._dataset_checkpoint_configs[dataset_name], state_dict | ||
| ) | ||
| ) |
There was a problem hiding this comment.
Restore mutates shared dataset context
Medium Severity
Restore writes checkpoint_config and _execution_idx onto the original dataset DataContext. That context is shared by Dataset.copy and by derived datasets from _from_parent, so a validation split from the same pipeline can skip train's already-consumed rows during mid-epoch resume, and later operations on the same dataset keep leftover checkpoint state.
Reviewed by Cursor Bugbot for commit 5252da1. Configure here.
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
…mark (#66680) > Stacked on #66562 (and #66563). Only review the last commit: "[Train] Add mid-epoch resumption release test". ## Description Adds a nightly release test for mid-epoch resumption with data iterator checkpointing: `mid_epoch_resume_benchmark_{10M,3B}`. `release/train_tests/mid_epoch_resume_benchmark/microbenchmark.py` runs a `TorchTrainer` with 16 mock-GPU workers over a Parquet dataset of 10M or 3B rows, using `DataConfig(dataset_checkpoint_configs={"train": DatasetCheckpointConfig(id_column="id", ...)})`. - It saves a data checkpoint with `DataIterator.state_dict()` every `checkpoint_interval` batches and at the end of each epoch, and stores it in the Ray Train checkpoint. - It injects a failure 90% of the way through the epoch (`--error_at=0.9`) and resumes from the latest checkpoint with `ray.train.get_dataset_shard("train", state_dict=...)`. - **Correctness:** after training, it checks that each epoch's checkpoint files cover exactly `total_dataset_rows` rows, so every row is seen exactly once per epoch, even across the restart. - **Performance:** it reports the total duration and the time to first batch with and without a data checkpoint, which includes the checkpoint load time. Release test config: - One test entry with a `scale` matrix (`10M`, `3B`), nightly, `byod: gpu`, `anyscale_sdk_2026: true`, and a 2700s timeout. - Compute configs (`compute_configs/{10M,3B}.yaml`): an `m5.2xlarge` head node with no CPUs, plus 10 or 50 `m5.8xlarge` workers with `MOCK_GPU: 4` and a 64 GB object store. - `--generate_id_column` is supported by the script but not passed, since `DatasetCheckpointConfig(generate_id_column=True)` isn't implemented yet (it depends on #65885–#65888). ## Related issues Not a duplicate: there's no existing release test for data iterator checkpointing or mid-epoch resumption. Generated ID column support (and `--generate_id_column` in this release test) is stacked on this PR: #66800 ## Additional information Testing: - `pre-commit run` on the changed files: passed. - The release test itself hasn't been run yet. I'll trigger it before marking this ready. AI assistance (Claude Code) was used to develop this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Justin Yu <[email protected]>
#66800) > Stacked on #66680 (which is stacked on #66562 and #66563). Only review the last commit: "[Data][Train] Support generated ID columns for mid-epoch resumption". > > **Depends on the generated-ID checkpointing stack:** #66732 adds `CheckpointConfig(generated_id_column=...)`, and #66733 / #66736 skip committed rows on restore. This PR assumes that API and can't merge before #66732. ## Description Adds `DatasetCheckpointConfig(generate_id_column=True)` for mid-epoch resumption. Users whose datasets have no unique ID column can then checkpoint the data iterator with row IDs that Ray Data generates from each row's location in its Parquet file. Changes: - **`DatasetCheckpointConfig`:** `generate_id_column=True` no longer raises `NotImplementedError`. Only Parquet reads on the V2 datasource path are supported. - **`CheckpointingBatchIterator`:** when the ID column is generated, it's recorded in `BatchMetadata.row_ids` for checkpointing, then removed from the batch before it's yielded, so users only see their own columns. A user-provided `id_column` is kept. - **`DatasetManager._build_restoration_checkpoint_config`:** builds the dataset's `CheckpointConfig` with `generated_id_column=` instead of `id_column=` when generating. The config is set even when there's nothing to restore, because the reader needs it to generate the ID column. - **Release test:** `mid_epoch_resume_benchmark_{{scale}}` passes `--generate_id_column`. ## Related issues Not a duplicate: this adds Train-ingest support on top of the generated-ID checkpointing stack (#66732, #66733, #66736), which covers batch inference only. ## Additional information Tests (run locally, Python 3.11, macOS): - `pytest python/ray/data/tests/test_data_iterator_checkpointer.py`: 25 passed. This includes the new `test_generated_id_column_removed_from_batches`, which checks that the column is removed from batches when generated and kept otherwise, and that the IDs are checkpointed either way. - `RAY_TRAIN_V2_ENABLED=1 pytest python/ray/train/v2/tests/test_dataset_checkpointing.py python/ray/train/v2/tests/test_dataset_manager.py`: - **On this branch alone, all e2e cases fail** with `TypeError: CheckpointConfig.__init__() got an unexpected keyword argument 'generated_id_column'`, because that argument comes from #66732. This is expected until #66732 lands. - With a temporary stand-in `generated_id_column=None` parameter on `CheckpointConfig` (not committed): 12 passed. The only 2 failures were the two `generate_id_column=True` e2e cases, which need the generated-ID reader support from that stack. - `pre-commit run` on the changed files: passed. AI assistance (Claude Code) was used to develop this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Justin Yu <[email protected]> Signed-off-by: Goutam <[email protected]> Co-authored-by: Goutam <[email protected]>


Description
Adds mid-epoch resumption to Ray Train V2 through data iterator checkpointing.
User-facing API:
Changes:
ray.train.get_dataset_shard(dataset_name, state_dict=None), with a newDatasetShardMetadata.state_dictfield.DataConfig(dataset_checkpoint_configs=...). It raisesNotImplementedErrorfor datasets that aren't indatasets_to_split, since onlystreaming_splitplans support checkpointing.ray.train.DatasetCheckpointConfig(defined inray.data.checkpoint.interfaces), exported with V2 only and added to the Train API reference (doc/source/train/api/config.md). It's annotatedPublicAPI(stability="alpha")where it's defined in Ray Data ([data] Mid-epoch resumption (1/n): Add data iterator checkpointing #66563), which also whitelists it in the Data API docs check since it's documented here. Like the otherray.trainexports, its__module__is set toray.train, so it shows up and pickles asray.train.DatasetCheckpointConfig.DatasetManagerimports the data iterator checkpointer lazily, following [Data][Train] Remove top-level ray.data imports to decouple Ray Train from Ray Data #60292, which keepsray.dataimports out of module scope in Ray Train.DatasetManager:CheckpointConfigfrom the state dict (partition filter,_should_restore) and sets_execution_idxso file shuffle order can be reproduced.RowIDBasedDataIteratorCheckpointerto each rank's iterator.DatasetsCallback:checkpoint_pathto{experiment_fs_path}/ray_data_checkpoints/{dataset_name}, on theRunConfigstorage filesystem. If the user setscheckpoint_pathbut notoverride_filesystem, the filesystem is inferred from the path instead.ValueErrorif two datasets use the samecheckpoint_path, since the checkpoint files aren't partitioned by dataset.state_dictpassed on a laterget_dataset_shardcall.Related issues
Not a duplicate: I searched open and closed PRs for "iterator checkpoint", "mid-epoch" and "state_dict" and found nothing overlapping.
The release test for this feature is stacked on this PR: #66680
Additional information
Tests (run locally, Python 3.11, macOS):
RAY_TRAIN_V2_ENABLED=1 pytest python/ray/train/v2/tests/test_dataset_checkpointing.py: 6 passed. This covers e2e restore from mid-epoch and from an epoch boundary with injected failures, checkpoint path and filesystem defaults,DataConfigvalidation, and data-order reproducibility after restore.pre-commit runon all changed files: passedAI assistance (Claude Code) was used to develop this change.
🤖 Generated with Claude Code