Skip to content

[data] Mid-epoch resumption (1/n): Add data iterator checkpointing - #66563

Merged
justinvyu merged 14 commits into
ray-project:masterfrom
justinvyu:justinvyu/data-iterator-checkpoint
Oct 7, 2026
Merged

justinvyu merged 14 commits into
ray-project:masterfrom
justinvyu:justinvyu/data-iterator-checkpoint

Conversation

@justinvyu

@justinvyu justinvyu commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds data iterator checkpointing to Ray Data, which is the Data half of mid-epoch resumption for training ingest.

Save side (new):

  • DataIterator.state_dict() (alpha) returns the iterator's checkpoint state. Checkpointing is turned on internally with DataIterator._enable_checkpointing(checkpointer).
  • RowIDBasedDataIteratorCheckpointer (ray/data/checkpoint/data_iterator_checkpointer.py) records the row IDs of every yielded batch. A background thread writes them to Parquet files laid out as rank={r}/epoch={e}/checkpoint={c}/chunk_{k}.parquet. state_dict() flushes and commits the current checkpoint directory, then returns {epoch_idx, checkpoint_idx, ...}.
  • CheckpointingBatchIterator (ray/data/checkpoint/iterator.py) hooks into BatchIterator to attach the row IDs to each batch's metadata and to tell the checkpointer when an epoch starts and ends. DataIterator uses it only when a checkpointer is attached, so iterators without checkpointing behave exactly as before.
  • DatasetCheckpointConfig (in ray/data/checkpoint/interfaces.py) holds the checkpointer's config. Ray Train exposes it as ray.train.DatasetCheckpointConfig in the stacked follow-up PR. generate_id_column=True raises NotImplementedError for now (see below).

Restore side: this reuses the existing CheckpointConfig(id_column, checkpoint_path_partition_filter) restore path on streaming_split plans. The partition filter comes from the state dict and matches epoch == e and checkpoint <= c.

Epoch handling: a private _should_restore flag on CheckpointConfig:

  • If it's False, the planner skips loading checkpoints and filtering rows, but still plans the checkpoint writer. Train sets this when it's starting from scratch or restoring at an epoch boundary.
  • LoadCheckpointCallback.after_execution_succeeds sets it to False, so only the first epoch after resuming skips checkpointed rows. Without this, every later epoch would re-apply the restore filter and silently drop those rows.
  • This doesn't change batch inference: each Dataset deep-copies the DataContext when it's created, so the flag only changes for the dataset that just ran. A rerun builds a new dataset from the original config and still restores, as test_checkpoint_restore_after_full_execution checks.

Other notes:

Follow-ups (not in this PR): remove the dependency of ray.data on Ray Train's storage helpers, add a real restore API instead of the private flag, derive epoch_idx from the dataset's _execution_idx instead of tracking it in the checkpointer, and support generate_id_column once #65888 lands.

Related issues

Not a duplicate: I searched open and closed PRs for "iterator checkpoint", "mid-epoch" and "state_dict" and found nothing overlapping. The related generated-ID checkpointing stack (#65885 (reverted in #66183), #65886, #65887, #65888) covers batch inference restore with auto-generated IDs. It doesn't add iterator checkpointing or per-epoch restore handling. Both touch planner.py and load_checkpoint_callback.py, so whichever lands second will need a small rebase.

The Train integration is stacked on this PR: #66562

AI assistance (Claude Code) was used to develop this change.

🤖 Generated with Claude Code

@justinvyu justinvyu changed the title [Data] Add data iterator checkpointing for mid-epoch resumption [data] Mid-epoch resumption (1/n): Add data iterator checkpointing Sep 29, 2026
@justinvyu
justinvyu marked this pull request as ready for review October 2, 2026 19:26
@justinvyu
justinvyu requested a review from a team as a code owner October 2, 2026 19:26

@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 row-ID-based data iterator checkpointing mechanism for training ingest in Ray Data, allowing users to save and restore the state of data iteration mid-epoch. It adds the DataIteratorCheckpointer interface, a concrete RowIDBasedDataIteratorCheckpointer that asynchronously flushes yielded row IDs to Parquet files, and a CheckpointingBatchIterator to manage the checkpointing lifecycle during iteration. Additionally, it updates the query planner to support conditional restoration and adds comprehensive unit tests. The review feedback suggests two improvements: validating that checkpoint_path is not None to prevent cryptic TypeErrors, and replacing an assertion with a user-friendly ValueError when verifying tabular datasets to handle non-tabular inputs more gracefully.

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.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Oct 3, 2026

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

@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 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 8fa60ce. Configure here.

assert batch.metadata.row_ids is not None, batch.metadata

self._should_update_state_dict = True
self._row_ids_staging_queue.put(batch.metadata.row_ids)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Queue pins full batch tables

Medium Severity

record_yielded_batch enqueues the select view of each batch's row IDs on an unbounded queue, and deepcopy_array only runs later on the flush thread. That view can keep the original full-width batch buffers alive (the Arrow issue cited next to deepcopy_array), so a slow checkpoint write lets many large training batches stay pinned until the background thread catches up.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8fa60ce. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

wrote this down as a followup

file-size or when the main thread requests a forced flush.
"""
staged_row_ids_size_bytes = 0
staged_row_id_batches: List[pa.Array] = []

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.

should be able to use pa_list <pa_list<>> instead of py_list<pa_list<>>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I see I just create a chunked pyarrow array after from the py_lists, we can update this in a followup if there's a significant diff

@justinvyu
justinvyu enabled auto-merge (squash) October 7, 2026 00:31
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 7, 2026
@github-actions
github-actions Bot disabled auto-merge October 7, 2026 07:07
@justinvyu
justinvyu enabled auto-merge (squash) October 7, 2026 07:10
@github-actions
github-actions Bot disabled auto-merge October 7, 2026 07:13
@justinvyu
justinvyu enabled auto-merge (squash) October 7, 2026 07:45
@justinvyu
justinvyu requested a review from a team as a code owner October 7, 2026 17:26
@github-actions
github-actions Bot disabled auto-merge October 7, 2026 17:26
@justinvyu
justinvyu enabled auto-merge (squash) October 7, 2026 17:26
@justinvyu
justinvyu merged commit 5ca60cf into ray-project:master Oct 7, 2026
7 checks passed
@justinvyu
justinvyu deleted the justinvyu/data-iterator-checkpoint branch October 7, 2026 18:52
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 16, 2026
…ng committed work at the source (#66736)

Follow-up to 1/4 (#66732) and 2/4 (#66733), both merged. 4/4 (#66734) is
an independent speed-up that lands last; this PR doesn't need it.

## Why are these changes needed?

This switches the feature on. A resumed `generated_id_column` job now
skips work it already committed, as early as possible. It doesn't run
the actor-pool `CheckpointFilter` that the `id_column` path applies to
every row.

## What changes

- **Planner routing** (`planner.py`). Generated-ID jobs get:
- `ListFiles` → `plan_list_files_op_with_done_read_units`: passes the
checkpoint's done unit ids as `EXCLUDED_READ_UNIT_IDS_KWARG_NAME` (the
hook from #66398). Fully committed files are never listed, and fully
committed row groups are never read.
- `ReadFiles` → `plan_read_files_op_with_done_rows`: the normal read
followed by a `DropCommittedRows` step for row groups that were only
partly committed.
- Each row's generated ID names its file, row group and `row_id`, so the
step looks up the row group's mask and drops rows where `mask[row_id]`
is set.
- The step fuses into the read task
(`ReadFilesParquetV2->DropCommittedRows->...`), so no extra stage runs.
- Thanks @AarryaSaraf for suggesting this over a new reader hook (the
former 4/5, #66735, now closed).
- The checkpoint's masks arrive as an Arrow table; each task indexes
them once (`_partial_mask_lookup`) and reuses the lookup for every
block. Masks stay numpy.
  - `Write` → the existing checkpoint two-phase commit.
- The `id_column` path is unchanged. 1/4's interim write-only gate is
removed.
- **Listing accepts Arrow ids** (`listing_utils.py`): the checkpoint
passes done unit ids as an Arrow array. Listing converts them to Python
strings before building its lookup set; a set built straight from an
Arrow array would hold Arrow values and never match.
  
- **Loading:** `LoadCheckpointCallback` loads the checkpoint once when
execution starts (`load_generated_id_checkpoint`, from 2/4). Both plan
functions read it through task kwargs set lazily
(`add_map_task_kwargs_fn`), because it isn't loaded at planning time. A
crashed run's pending checkpoints are still cleaned up while planning,
before the load.
- **Runs that don't restore** (`CheckpointConfig._should_restore`, from
#66563): after a successful run sets it to `False` (e.g. later training
epochs), the planner plans only the checkpoint write, as for
`id_column`, and `LoadCheckpointCallback` skips loading the generated-ID
checkpoint, since no operator reads it.
- **Validation:** plans whose sources aren't V2 Parquet reads
(`ReadFiles` over a `ParquetScanner`) raise `InvalidCheckpointingConfig`
with a pointer to `id_column`. This covers the V1 `Read` path and
non-Parquet V2 scanners.
- **Docs:** a "Checkpoint without an ID column" section in
`doc/source/data/execution-configurations.md`.

Note: like the `id_column` path's filter, `DropCommittedRows` runs after
the read, so a `limit` pushed into the read counts rows before they're
dropped.

## Related issue number

N/A. Not a duplicate (see 1/4). Replaces my pre-reorg drafts #65886,
#65887 and #65888.

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit on all changed files: clean. `vale` (v3.17.1,
as in CI) on the docs page: 0 errors, 0 warnings, 0 suggestions.
- [x] AI assistance (Claude Code) was used for the development of this
PR. I, Abhishek Verma, am the human submitter signing off on it: I have
reviewed every changed line, run the tests below locally, and can defend
the change end-to-end.
- Testing:
- `pytest python/ray/data/tests/unit/test_generated_id_checkpoint.py`:
15 passed. New: masked rows dropped per row group in a block mixing row
groups and files; rows past a short mask kept; no matching mask means no
change; mask lookup across table chunks.
- `test_read_units.py`: listing skips done units whether the ids arrive
as a set, an Arrow array, or a chunked array. The Arrow cases fail
without the conversion.
- With `_should_restore=False`, a run ignores the kept checkpoint, reads
every row, never loads the checkpoint, and still writes checkpoints. I
checked that this test fails without the callback fix.
- On current master, `pytest python/ray/data/tests/test_checkpoint.py
python/ray/data/tests/test_data_iterator_checkpointer.py
python/ray/data/tests/unit/test_generated_id_checkpoint.py
python/ray/data/tests/unit/datasource_v2`: 299 passed, 1 failed. The
failure, `test_skip_checkpoint_flag[s3]`, is a pre-existing local
moto-S3 flake that also fails on unmodified master.
  - New end-to-end tests in `python/ray/data/tests/test_checkpoint.py`:
- Crash partway, then rerun: no missing rows, and the checkpoint is
deleted on success.
- Resume skips a fully committed file, a committed row group, and the
committed rows of a partly committed row group, and reads a never-seen
file in full. The output is exactly the uncommitted rows. I checked that
this test fails with `DropCommittedRows` disabled.
    - A rerun after a full success writes nothing.
- The plan has no `CheckpointFilter` op, and `DropCommittedRows` is
fused into the read.
    - Non-Parquet and V1 inputs are rejected.
- `pytest python/ray/data/tests/unit/test_generated_id_checkpoint.py`:
15 passed. New: masked rows dropped per row group in a block mixing row
groups and files; rows past a short mask kept; no matching mask means no
change; mask lookup across table chunks.
- Block sizing: a `generated_id_column` read produces the same number of
blocks per task as a plain read (`DropCommittedRows` keeps
`target_max_block_size`).
- `test_read_units.py`: listing skips done units whether the ids arrive
as a set, an Arrow array, or a chunked array. The Arrow cases fail
without the conversion.
- With `_should_restore=False`, a run ignores the kept checkpoint, reads
every row, never loads the checkpoint, and still writes checkpoints. I
checked that this test fails without the callback fix.
- On current master, `pytest python/ray/data/tests/test_checkpoint.py
python/ray/data/tests/test_data_iterator_checkpointer.py
python/ray/data/tests/unit/test_generated_id_checkpoint.py
python/ray/data/tests/unit/datasource_v2`: 299 passed, 1 failed. The
failure, `test_skip_checkpoint_flag[s3]`, is a pre-existing local
moto-S3 flake that also fails on unmodified master.
- `pytest python/ray/data/tests/unit
python/ray/data/tests/datasource_v2`: 1500 passed.
- Five modules didn't collect locally for missing optional dependencies
(torch, pyiceberg, freezegun).
- Two failures in `test_dynamic_work_queue.py`, which also fail on
unmodified master.
- **Together with 4/4** (local combined branch): 237 DSv2/unit and 38
checkpoint tests passed. In a manual resume run (4 files × 4 row groups,
16 write tasks), I deleted 6 committed checkpoint files and the rerun
wrote **exactly those 6,000 rows**.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Abhishek Verma <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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 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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants