Skip to content

[data][train] Mid-epoch resumption (3/n): Add release test microbenchmark - #66680

Merged
goutamvenkat-anyscale merged 1 commit into
ray-project:masterfrom
justinvyu:justinvyu/mid-epoch-resume-release-test
Oct 31, 2026
Merged

goutamvenkat-anyscale merged 1 commit into
ray-project:masterfrom
justinvyu:justinvyu/mid-epoch-resume-release-test

Conversation

@justinvyu

@justinvyu justinvyu commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

@justinvyu
justinvyu force-pushed the justinvyu/mid-epoch-resume-release-test branch 5 times, most recently from cb98ce9 to b19823a Compare October 5, 2026 22:50
@justinvyu
justinvyu marked this pull request as ready for review October 5, 2026 22:53
@justinvyu
justinvyu requested review from a team as code owners October 5, 2026 22:53
@justinvyu justinvyu changed the title [Train] Add mid-epoch resumption release test [data][train] Mid-epoch resumption (3/n): Add release test microbenchmark Oct 5, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +106 to +109
checkpoint_config.checkpoint_path = Path(
storage_context.experiment_fs_path,
"ray_data_checkpoints",
).as_posix()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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"
)

Comment on lines +324 to +328
self._flush_thread = threading.Thread(
target=self._process_row_ids_from_queue,
daemon=True,
name="DataIteratorCheckpointer-flush",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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:

  1. Use a static method or helper function for the thread target that only holds a weakref to self.
  2. Define a shutdown sentinel (e.g., _SHUTDOWN_SENTINEL = object()) to cleanly stop the thread.
  3. Implement thread cleanup in __del__.
Suggested change
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",
)

Comment on lines +145 to +149
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
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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,
        )

Comment on lines +76 to +80
if self._datasets_to_split != "all":
unsharded_datasets = set(self.dataset_checkpoint_configs.keys()) - set(
self._datasets_to_split
)
if unsharded_datasets:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.


run:
timeout: 2700
script: RAY_TRAIN_V2_ENABLED=1 python microbenchmark.py --num_rows={{scale}} --error_at=0.9 --num_epochs=1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b19823a. Configure here.

@justinvyu
justinvyu force-pushed the justinvyu/mid-epoch-resume-release-test branch from b19823a to a82059b Compare October 5, 2026 23:44
@ray-gardener ray-gardener Bot added train Ray Train Related Issue release-test release test labels Oct 6, 2026
@justinvyu
justinvyu force-pushed the justinvyu/mid-epoch-resume-release-test branch 2 times, most recently from b49e1ed to 0b1be31 Compare October 6, 2026 18:53

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0b1be31. Configure here.

@justinvyu
justinvyu force-pushed the justinvyu/mid-epoch-resume-release-test branch 2 times, most recently from 4e3a731 to 10fee95 Compare October 7, 2026 17:27
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 22, 2026
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 24, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 30, 2026
…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]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the justinvyu/mid-epoch-resume-release-test branch from 10fee95 to 2519d6b Compare October 31, 2026 00:47
@goutamvenkat-anyscale goutamvenkat-anyscale added the go add ONLY when ready to merge, run all tests label Oct 31, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale removed request for a team October 31, 2026 00:48
@goutamvenkat-anyscale
goutamvenkat-anyscale enabled auto-merge (squash) October 31, 2026 00:49
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit c8e5c11 into ray-project:master Oct 31, 2026
7 of 8 checks passed
goutamvenkat-anyscale added a commit that referenced this pull request Oct 31, 2026
#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]>
elliot-barn pushed a commit that referenced this pull request Nov 4, 2026
…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]>
elliot-barn pushed a commit that referenced this pull request Nov 5, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests release-test release test train Ray Train Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants