Skip to content

[data][train] Mid-epoch resumption (2/n): Add save/load APIs on the training worker side - #66562

Merged
goutamvenkat-anyscale merged 16 commits into
ray-project:masterfrom
justinvyu:justinvyu/train-mid-epoch-resumption
Oct 30, 2026
Merged

goutamvenkat-anyscale merged 16 commits into
ray-project:masterfrom
justinvyu:justinvyu/train-mid-epoch-resumption

Conversation

@justinvyu

@justinvyu justinvyu commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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:

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 ([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 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 [Data][Train] Remove top-level ray.data imports to decouple Ray Train from Ray Data #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

@justinvyu justinvyu changed the title [Train] Support mid-epoch resumption with dataset checkpoint configs [train] Mid-epoch resumption (2/n): Add save/load APIs on the training worker side Sep 29, 2026
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from 7dfc2d1 to ab3d0dc Compare October 2, 2026 18:46
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from ab3d0dc to 2f9999c Compare October 2, 2026 18:54
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from 2f9999c to a58a022 Compare October 2, 2026 19:23
@justinvyu
justinvyu marked this pull request as ready for review October 2, 2026 19:30
@justinvyu
justinvyu requested review from a team as code owners October 2, 2026 19:30

@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 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__)

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

Define a shutdown sentinel at the module level to cleanly terminate the background flush thread when the checkpointer is garbage collected.

Suggested change
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
_SHUTDOWN_SENTINEL = object()

Comment on lines +263 to +264
self._checkpoint_config = checkpoint_config
self._id_column = checkpoint_config.id_column

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

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

Comment on lines +317 to +321
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

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.

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_helper,
args=(
weakref.ref(self),
self._row_ids_staging_queue,
self._flush_completed_event,
_SHUTDOWN_SENTINEL,
),
daemon=True,
name="DataIteratorCheckpointer-flush",
)

Comment on lines +382 to +386
call_with_retry(
_write,
description=f"Write checkpoint file: {checkpoint_path}",
match=DataContext.get_current().retried_io_errors,
)

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

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.

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

Comment on lines +391 to +436
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

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

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

Comment on lines +586 to +588
def __del__(self):
if self._delete_threadpool:
self._delete_threadpool.shutdown(wait=True)

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

Ensure the background flush thread is cleanly shut down when the checkpointer is garbage collected by putting the shutdown sentinel into the queue.

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

Comment thread python/ray/data/checkpoint/iterator.py Resolved

@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.

@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from a58a022 to c348e59 Compare October 2, 2026 20:03
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation train Ray Train Related Issue data Ray Data-related issues labels Oct 3, 2026
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from c348e59 to 009ee6c Compare October 5, 2026 22:20

@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.

@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from 009ee6c to a8249c7 Compare October 5, 2026 22:46
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from a8249c7 to 148225d Compare October 5, 2026 22:50
@justinvyu justinvyu changed the title [train] Mid-epoch resumption (2/n): Add save/load APIs on the training worker side [data][train] Mid-epoch resumption (2/n): Add save/load APIs on the training worker side Oct 5, 2026
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from a688457 to fdca178 Compare October 6, 2026 18:53
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from fdca178 to 8c4ef0e Compare October 7, 2026 07:47
@justinvyu
justinvyu force-pushed the justinvyu/train-mid-epoch-resumption branch from 8c4ef0e to 3861a06 Compare October 7, 2026 17:26
@justinvyu
justinvyu requested a review from a team as a code owner October 7, 2026 17:26

@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.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5252da1. Configure here.

self._build_restoration_checkpoint_config(
self._dataset_checkpoint_configs[dataset_name], state_dict
)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5252da1. Configure here.

@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 goutamvenkat-anyscale added the go add ONLY when ready to merge, run all tests label Oct 30, 2026
@goutamvenkat-anyscale
goutamvenkat-anyscale enabled auto-merge (squash) October 30, 2026 22:13
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 2bdf261 into ray-project:master Oct 30, 2026
8 checks passed
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 31, 2026
…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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues docs An issue or change related to documentation go add ONLY when ready to merge, run all tests 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.

3 participants