Repository navigation
[data][train] Mid-epoch resumption (3/n): Add release test microbenchmark - #66680
Conversation
cb98ce9 to
b19823a
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces a checkpointing mechanism for data iterators in Ray Data, enabling mid-epoch resumption for training jobs. It includes a new DataIteratorCheckpointer interface, a RowIDBasedDataIteratorCheckpointer implementation, and updates to Ray Train's DataConfig and DatasetsCallback to integrate this functionality. I have identified several critical issues in the implementation, including a potential cloud URI corruption bug, a memory leak caused by a reference cycle in the background thread, and potential runtime crashes due to unsafe dictionary access in path filtering and None handling in DataConfig.
| checkpoint_config.checkpoint_path = Path( | ||
| storage_context.experiment_fs_path, | ||
| "ray_data_checkpoints", | ||
| ).as_posix() |
There was a problem hiding this comment.
Cloud URI Path Corruption Bug
Using pathlib.Path on cloud URIs (e.g., s3://... or gs://...) is unsafe because Path is designed for local filesystems and will collapse double slashes // into a single slash / (e.g., s3://bucket becomes s3:/bucket). This corrupts the URI and causes subsequent cloud storage operations to fail.
Use simple string manipulation to append the subpath safely instead.
| checkpoint_config.checkpoint_path = Path( | |
| storage_context.experiment_fs_path, | |
| "ray_data_checkpoints", | |
| ).as_posix() | |
| checkpoint_config.checkpoint_path = ( | |
| storage_context.experiment_fs_path.rstrip("/") | |
| + "/ray_data_checkpoints" | |
| ) |
| self._flush_thread = threading.Thread( | ||
| target=self._process_row_ids_from_queue, | ||
| daemon=True, | ||
| name="DataIteratorCheckpointer-flush", | ||
| ) |
There was a problem hiding this comment.
Memory and Thread Leak due to Reference Cycle
The background thread self._flush_thread is initialized with target=self._process_row_ids_from_queue, which is a bound method of self. This creates a strong reference cycle:
self -> self._flush_thread -> self._process_row_ids_from_queue (bound method) -> self.
Because the background thread runs an infinite loop (while True:), it will never terminate as long as the process is alive. Consequently, the RowIDBasedDataIteratorCheckpointer instance and all its associated resources (such as the queue, the PyArrow filesystem, etc.) will never be garbage collected, leading to a severe memory and thread leak every time a checkpointer is created.
To fix this:
- Use a static method or helper function for the thread target that only holds a
weakreftoself. - Define a shutdown sentinel (e.g.,
_SHUTDOWN_SENTINEL = object()) to cleanly stop the thread. - Implement thread cleanup in
__del__.
| 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_static, | |
| args=(weakref.ref(self), self._row_ids_staging_queue), | |
| daemon=True, | |
| name="DataIteratorCheckpointer-flush", | |
| ) |
| filter_fn=lambda partitioned_path: ( | ||
| int(partitioned_path[self.EPOCH_PATH_KEY]) == self.epoch_idx | ||
| and int(partitioned_path[self.CHECKPOINT_IDX_PATH_KEY]) | ||
| <= self.checkpoint_idx | ||
| ), |
There was a problem hiding this comment.
Robust Partition Path Filtering
If there are any non-partitioned files, system files (like .DS_Store), or metadata files in the checkpoint directory, partitioned_path will not contain the expected partition keys. Accessing them directly with partitioned_path[self.EPOCH_PATH_KEY] will raise a KeyError and crash the dataset restoration.
Using a safer .get() check with a try-except block prevents unexpected crashes.
def filter_fn(partitioned_path):
epoch_val = partitioned_path.get(self.EPOCH_PATH_KEY)
ckpt_val = partitioned_path.get(self.CHECKPOINT_IDX_PATH_KEY)
if epoch_val is None or ckpt_val is None:
return False
try:
return int(epoch_val) == self.epoch_idx and int(ckpt_val) <= self.checkpoint_idx
except ValueError:
return False
return PathPartitionFilter.of(
filter_fn=filter_fn,
style=PartitionStyle.HIVE,
)| if self._datasets_to_split != "all": | ||
| unsharded_datasets = set(self.dataset_checkpoint_configs.keys()) - set( | ||
| self._datasets_to_split | ||
| ) | ||
| if unsharded_datasets: |
There was a problem hiding this comment.
Safe Handling of None/Empty _datasets_to_split
If self._datasets_to_split is None (which can happen if the user configures it to disable splitting), calling set(self._datasets_to_split) will raise a TypeError: 'NoneType' object is not iterable.
Adding a guard or defaulting to an empty set prevents this potential crash.
if self._datasets_to_split != "all":
datasets_to_split_set = set(self._datasets_to_split) if self._datasets_to_split is not None else set()
unsharded_datasets = set(self.dataset_checkpoint_configs.keys()) - datasets_to_split_set|
|
||
| run: | ||
| timeout: 2700 | ||
| script: RAY_TRAIN_V2_ENABLED=1 python microbenchmark.py --num_rows={{scale}} --error_at=0.9 --num_epochs=1 |
There was a problem hiding this comment.
Cluster start does not wait
Medium Severity
The 10- and 50-worker configs never set wait_for_nodes, unlike the neighboring Train release tests. The script can start before Ray has registered every node, so the 3B run in particular may time out or starve for MOCK_GPU and CPU.
Reviewed by Cursor Bugbot for commit b19823a. Configure here.
| parser = argparse.ArgumentParser() | ||
| parser.add_argument("--num_rows", type=str, default="10M", choices=["10M", "3B"]) | ||
| parser.add_argument("--num_epochs", type=int, default=2) | ||
| parser.add_argument("--disable_data_checkpointing", action="store_true") |
There was a problem hiding this comment.
Unused disable checkpointing flag
Low Severity
--disable_data_checkpointing is defined but never read. DataConfig.dataset_checkpoint_configs is always populated, so the flag does not disable iterator checkpointing.
Reviewed by Cursor Bugbot for commit b19823a. Configure here.
b19823a to
a82059b
Compare
b49e1ed to
0b1be31
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
Reviewed by Cursor Bugbot for commit 0b1be31. Configure here.
| global_rows_processed += ( | ||
| len(batch["id"]) * ray.train.get_context().get_world_size() | ||
| ) | ||
| global_epochs_processed = global_rows_processed / total_dataset_rows |
There was a problem hiding this comment.
Row accounting assumes even worker shards
Medium Severity
Each worker treats global_rows_processed as its local batch size times world_size. That equals the true dataset size only when streaming_split gives every rank the same row count. Parquet shards are split by files and blocks, not exact rows, so the end-of-epoch modulo assertion can fail on a correct run, and --error_at=0.9 can fire at the wrong progress point.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 0b1be31. Configure here.
4e3a731 to
10fee95
Compare
|
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. |
…raining worker side (#66562) > Stacked on #66563. Only review the last commit: "[Train] Support mid-epoch resumption with dataset checkpoint configs". ## Description Adds mid-epoch resumption to Ray Train V2 through data iterator checkpointing. User-facing API: ```python trainer = TorchTrainer( train_fn, datasets={"train": ds}, dataset_config=ray.train.DataConfig( dataset_checkpoint_configs={ "train": ray.train.DatasetCheckpointConfig(id_column="id") } ), ) def train_fn(config): state_dict = ... # loaded from the latest ray.train checkpoint, if any it = ray.train.get_dataset_shard("train", state_dict=state_dict) for batch in it.iter_torch_batches(): ... # Save alongside the model checkpoint. data_state = it.state_dict() ``` Changes: - `ray.train.get_dataset_shard(dataset_name, state_dict=None)`, with a new `DatasetShardMetadata.state_dict` field. - `DataConfig(dataset_checkpoint_configs=...)`. It raises `NotImplementedError` for datasets that aren't in `datasets_to_split`, since only `streaming_split` plans support checkpointing. - `ray.train.DatasetCheckpointConfig` (defined in `ray.data.checkpoint.interfaces`), exported with V2 only and added to the Train API reference (`doc/source/train/api/config.md`). It's annotated `PublicAPI(stability="alpha")` where it's defined in Ray Data (#66563), which also whitelists it in the Data API docs check since it's documented here. Like the other `ray.train` exports, its `__module__` is set to `ray.train`, so it shows up and pickles as `ray.train.DatasetCheckpointConfig`. - `DatasetManager` imports the data iterator checkpointer lazily, following #60292, which keeps `ray.data` imports out of module scope in Ray Train. - `DatasetManager`: - Restore: builds the restore `CheckpointConfig` from the state dict (partition filter, `_should_restore`) and sets `_execution_idx` so file shuffle order can be reproduced. - Save: attaches a `RowIDBasedDataIteratorCheckpointer` to each rank's iterator. - `DatasetsCallback`: - Defaults `checkpoint_path` to `{experiment_fs_path}/ray_data_checkpoints/{dataset_name}`, on the `RunConfig` storage filesystem. If the user sets `checkpoint_path` but not `override_filesystem`, the filesystem is inferred from the path instead. - Raises a `ValueError` if two datasets use the same `checkpoint_path`, since the checkpoint files aren't partitioned by dataset. - The shard provider rejects a `state_dict` passed on a later `get_dataset_shard` call. ## 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, `DataConfig` validation, and data-order reproducibility after restore. - `pre-commit run` on all 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: Justin Yu <[email protected]>
10fee95 to
2519d6b
Compare
c8e5c11
into
ray-project:master
#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]>
…ge (#67805) ## Problem #67518 removed the `gpu` BYOD type, but `mid_epoch_resume_benchmark_{10M,3B}` still uses it. #66680 added those tests after #67517 had migrated the others. So `//release:test_config` fails on master: ``` Failed to validate test mid_epoch_resume_benchmark_10M: Invalid BYOD type: gpu ``` ## Solution Move the test to `torch-cu128`, like the other Train tests in #67517. `torch-cu128` requires Python 3.11, so bump `python` from 3.10. The benchmark only needs Ray and torch, which the ray-torch image provides. ## Validation `bazel test //release:test_config` fails on master with the error above and passes with this change. No existing PR addresses this. AI assistance (Claude Code) was used. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Jeffrey Wang <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…and k8s Serve release tests (#67773) ## Problem Four Serve release tests fail on every run: | Test | Cause | Last pass | |---|---|---| | `pytest_serve_multi_deployment_1k_noop_replica.gce` | Replicas require the custom `worker` resource (#46130), but the GCE config never declared it, so they are unschedulable. | Never since #46130 | | `serve_controller_benchmark_haproxy.gce` | Points at a single 16-CPU node; the benchmark needs ~205 workers. It stalls at 34/51 replicas. | Never (added in #61368) | | `video_analysis_pipeline.gce` | Invalid instance type (`g2-standard-4`), wrong region, and the app reads from S3. | Never | | `k8s_serve_ha_test` | `prepare.sh` fails with `jq: command not found`, then needs `kubectl` and a GKE cluster. | Jul 2023 | ## Fix - Add `resources: {CPU: 32, worker: 1}` to `compute_tpl_32_cpu_gce.yaml`, matching the AWS config. - Remove the GCE variations of the controller benchmark and video analysis tests. The AWS variations cover them. - Remove `k8s_serve_ha_test` and `release/k8s_tests/`, which nothing else uses. `read_and_validate_release_test_collection` passes on the updated `release_tests.yaml`, apart from the master breakage below. ## Premerge `//release:test_config` fails on master, not from this PR: `mid_epoch_resume_benchmark_{10M,3B}` (#66680) still use the `gpu` BYOD type that #67518 removed. Moving them to `torch-cu128` on Python 3.11, as #67517 did for the rest, fixes it. This PR will be rebased once master is fixed. Signed-off-by: qishengxhe <[email protected]>


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.pyruns aTorchTrainerwith 16 mock-GPU workers over a Parquet dataset of 10M or 3B rows, usingDataConfig(dataset_checkpoint_configs={"train": DatasetCheckpointConfig(id_column="id", ...)}).DataIterator.state_dict()everycheckpoint_intervalbatches and at the end of each epoch, and stores it in the Ray Train checkpoint.--error_at=0.9) and resumes from the latest checkpoint withray.train.get_dataset_shard("train", state_dict=...).total_dataset_rowsrows, so every row is seen exactly once per epoch, even across the restart.Release test config:
scalematrix (10M,3B), nightly,byod: gpu,anyscale_sdk_2026: true, and a 2700s timeout.compute_configs/{10M,3B}.yaml): anm5.2xlargehead node with no CPUs, plus 10 or 50m5.8xlargeworkers withMOCK_GPU: 4and a 64 GB object store.--generate_id_columnis supported by the script but not passed, sinceDatasetCheckpointConfig(generate_id_column=True)isn't implemented yet (it depends on [Data] [1/4] Addgenerated_id_columnto CheckpointConfig with V2 Parquet row-group IDs #65885–[Data] [4/4] Route generated-ID checkpointing in the planner, validate Parquet-only, add docs #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_columnin this release test) is stacked on this PR: #66800Additional information
Testing:
pre-commit runon the changed files: passed.AI assistance (Claude Code) was used to develop this change.
🤖 Generated with Claude Code