Skip to content

[train] Add checkpoint_frequency to RayTrainReportCallback - #66950

Merged
matthewdeng merged 8 commits into
ray-project:masterfrom
miggle711:fix/lightning-checkpoint-frequency
Oct 14, 2026
Merged

matthewdeng merged 8 commits into
ray-project:masterfrom
miggle711:fix/lightning-checkpoint-frequency

Conversation

@miggle711

@miggle711 miggle711 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

[train] Add checkpoint_frequency to RayTrainReportCallback

Why are these changes needed?

RayTrainReportCallback currently checkpoints on every training epoch, with no way to reduce checkpoint frequency for long runs where checkpointing (save + upload) is comparatively expensive relative to a training step.

The linked issue also asked for DDP rank "autodetection," citing a doc tip that manually checks global_rank == 0 before calling trainer.save_checkpoint(). I checked Lightning's own source (Strategy.save_checkpoint already gates the actual write on self.is_global_zero) and confirmed this is already handled correctly: calling save_checkpoint() unconditionally on every rank, which RayTrainReportCallback already does, is the documented, correct pattern (see the existing test_custom_checkpoint_callback test's own docstring: "A custom callback must save on every worker to avoid a DDP deadlock"). So this PR only adds the missing checkpoint_frequency, not rank-detection logic.

Change

  • Added checkpoint_frequency: int = 1 to RayTrainReportCallback.__init__ (default preserves current behavior: checkpoint every epoch).
  • on_train_epoch_end returns early, skipping the checkpoint save, ray.train.report, and the barrier, unless (trainer.current_epoch + 1) % self.checkpoint_frequency == 0. Metrics and checkpoint are therefore always reported together. Per review feedback, ray.train.report is not called on other epochs. All workers evaluate the same condition, so they stay in sync.
  • Raises TypeError if checkpoint_frequency is not an int (bools are rejected too) and ValueError if it is < 1.
  • Documented in the docstring that if max_epochs is not a multiple of checkpoint_frequency, the epochs after the last multiple are not reported or checkpointed.

Decisions to confirm

  • (trainer.current_epoch + 1) % checkpoint_frequency == 0 checkpoints on the Nth, 2Nth, 3Nth... epoch (1-indexed), not epoch 0. Open to using trainer.current_epoch % checkpoint_frequency == 0 instead if checkpointing on the first epoch is preferred.
  • If max_epochs is not a multiple of checkpoint_frequency, the trailing epochs are not reported. I can add a final report in on_train_end if preferred; I left it out to keep to the intended report cadence.

Not a duplicate

No open issue or PR covers this. Checked: PRs referencing #55875 by number, open PRs mentioning RayTrainReportCallback, open PRs mentioning checkpoint_frequency, and #55875's own comment thread (empty, no prior discussion).

Testing

  • test_report_callback_checkpoint_frequency: 6-epoch DDP run with checkpoint_frequency=3. Asserts only epochs 2 and 5 report a checkpoint.
  • test_report_callback_invalid_checkpoint_frequency: asserts invalid values raise (ValueError for 0, TypeError for non-int and bool).
$ pytest python/ray/train/tests/test_torch_lightning_train.py -k "checkpoint_frequency"
2 passed
$ RAY_TRAIN_V2_ENABLED=1 pytest python/ray/train/tests/test_torch_lightning_train.py -k "checkpoint_frequency"
2 passed

The GPU-only tests in this file (NCCL/CUDA) could not be run locally; they rely on CI.

Related issue number

Closes #55875

AI assistance was used for this change.

@miggle711
miggle711 requested a review from a team as a code owner October 13, 2026 12:09

@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 checkpoint_frequency parameter to RayTrainReportCallback in Ray Train's Lightning integration, allowing users to skip expensive checkpointing on non-matching epochs while still reporting metrics every epoch. The feedback suggests strengthening the input validation for checkpoint_frequency by explicitly checking for integer types and raising a TypeError for invalid types, as well as adding corresponding unit tests to verify this behavior.

Addresses Gemini Code Assist review feedback: a float or string
checkpoint_frequency previously passed construction silently (or
failed with a confusing TypeError deep in the modulo check), only
surfacing later inside training. Also guards against bool, since bool is an int subclass in Python and would otherwise silently pass isinstance(x, int).

Signed-off-by: miggle711 <[email protected]>

@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 714d6d0. Configure here.

@ray-gardener ray-gardener Bot added train Ray Train Related Issue community-contribution Contributed by the community labels Oct 13, 2026
ray.train.report() raises ValueError if validation is truthy but
checkpoint is None. When checkpoint_frequency skips an epoch's
checkpoint, validation must not be forwarded for that epoch either.

Signed-off-by: miggle711 <[email protected]>

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the PR.
I think for the _lightning_utils.py we should skip the ray.train.report for not should_checkpoint.
In v2, we've changed ray.train.report to require both a checkpoint and metrics as we don't want ray.train.report to be used as an experiment manager but as a fault tolerance solution.

With checkpoint_frequency > 1, only call ray.train.report on epochs where
a checkpoint is saved, so metrics and checkpoint are always reported
together. This also removes the validation workaround for epochs without
a checkpoint.

Signed-off-by: miggle711 <[email protected]>
@miggle711

Copy link
Copy Markdown
Contributor Author

Thanks for the PR. I think for the _lightning_utils.py we should skip the ray.train.report for not should_checkpoint. In v2, we've changed ray.train.report to require both a checkpoint and metrics as we don't want ray.train.report to be used as an experiment manager but as a fault tolerance solution.

Thanks for the review @pseudo-rnd-thoughts! I've updated _lightning_utils.py so ray.train.report is skipped entirely on non-checkpoint epochs. This means metrics and checkpoint are always reported together everycheckpoint_frequency epochs. The docstring and test are also updated to match.

Also, I added a caveat in the docstring, if max_epochs isn't a multiple of checkpoint_frequency, the trailing epochs aren't reported or checkpointed. I can add a final report in on_train_end if you'd like too.

All changes made in 70e42f3. :)

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

thanks for the update, could you make the following changes then LGTM

@miggle711

Copy link
Copy Markdown
Contributor Author

Hi @pseudo-rnd-thoughts, both requested changes have been made. :)

@pseudo-rnd-thoughts pseudo-rnd-thoughts added the go add ONLY when ready to merge, run all tests label Oct 14, 2026

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for making the changes @miggle711, LGTM

@matthewdeng
matthewdeng merged commit 94dd64d into ray-project:master Oct 14, 2026
7 checks passed
@miggle711
miggle711 deleted the fix/lightning-checkpoint-frequency branch October 15, 2026 00:14
dstrodtman added a commit that referenced this pull request Nov 4, 2026
## Description

This PR makes the `lint: API param coverage` step a required check by
removing `soft_fail: true`. The step was added in #64788 on 2026-08-11.
A comment in the step said to remove `soft_fail` "once the
false-positive rate is confirmed low." This PR measures that rate from
the step's CI history and fixes the four failure patterns the history
turned up.

While the step only warns, undocumented parameters still land on master.
#65633, #66602, and #66950 all merged with the check failing.

### Warn-phase metrics

These numbers come from every `premerge` build from 2026-08-11 to
2026-10-29, pulled from the Buildkite API.

| | Runs | PRs |
|---|--:|--:|
| Completed runs of the step | 3,453 | |
| Passed | 3,398 | |
| Failed | 55 | 23 |
| Canceled, which isn't a check outcome | 211 | |

Each failure falls into one of three groups:

| Failure type | PRs | Runs | Detail |
|---|--:|--:|---|
| Correct finding | 15 | 42 | A new parameter on a `@PublicAPI` callable
has no `Args:` entry. Two of these PRs, #65823 and #65839, were stacked
on #65633 before it merged and report its findings again. |
| False positive | 3 | 4 | #64399 flagged the `v` argument of a pydantic
`@field_validator`. #66255 flagged the private kwarg `_direct_http`.
#67258 flagged an option of the `ray start` Click command, which `help=`
documents. |
| Infrastructure | 5 | 9 | The step printed `could not determine
merge-base` and no findings. The branches of #65437 and #65809 forked
520 and 598 master commits before their builds. The step's `git fetch
--depth=500` makes the full CI clone shallow, so their merge-base wasn't
in the fetched history. |

That's 13 spurious failures out of 3,453 runs, about 0.4%, or 13 of 55
failures. Each one would block a PR once the step is required, so this
PR fixes all four patterns before removing `soft_fail`.

### Changes

- **`_`-prefixed parameters:** `api_param_coverage.py` skips parameters
whose names start with `_`. That's Ray's convention for private kwargs,
such as `ray.put(_owner=...)`, `tune.run(_remote=...)`, and
`Deployment.options(_internal=...)`. On master, 31 public callables have
such parameters.
- **Pydantic validators and Click commands:** The script skips callables
decorated with `field_validator`, `model_validator`, `validator`,
`root_validator`, `command`, or `group`. On master, this removes 59
callables from scope. All of them are Click commands, such as `ray
start` and `ray job submit`, or pydantic validators on Serve config
models. None of them is a Python API whose parameters a docstring
documents.
- **Property setters:** The script also skips callables decorated with
`@<name>.setter`. A setter's `value` is documented on the property's
getter, which is the docstring Sphinx renders, not in an `Args:` section
of its own.
- **Shallow-clone merge-base:** When `git merge-base` fails after the
depth-500 fetch, `ci/lint/lint.sh` runs `git fetch --unshallow` and
retries. A branch within 500 commits of the base never reaches that
path. The Python check still fails closed if the base can't be resolved
after that.
- **Step definition:** `.buildkite/lint.rayci.yml` drops `soft_fail:
true` and the warn-phase comment. The `--blocking` help text in
`cmd_check_api_param_coverage.py` no longer describes a warn phase.

## Related issues

Follow-up to #64788.

## Additional information

### Testing

- `pytest ci/ray_ci/doc/test_api_param_coverage.py`: 40 passed. That's
the 28 existing tests plus 12 new cases covering `_` params, each
validator spelling, Click command forms, and property setters. The test
comments name the real PR that motivated each one.
- **Replay against real PRs:** I ran the master and patched versions of
the check against the exact commit and base of every failing run in each
of the 18 PRs with findings. Master reproduces all 18 failures. The
patched check passes #64399, #66255, and #67258, and reports the same
findings as master on the other 15.
- **Merge-base fix:** In a local repo with 600 commits on `master` and a
branch forked at commit 50, `git fetch --depth=500` followed by `git
merge-base` fails, which reproduces the CI failure. With the new
`lint.sh` block, it resolves the correct fork commit. A branch forked 10
commits back resolves without the fallback.
- `pre-commit run` on the changed files passes, including ruff, black,
shellcheck, and docstyle.

### Duplicate check

`gh pr list --state open --search "param coverage"` and `--search
"api_param_coverage"` return no open PR that touches this check. The
script hasn't changed since #65391 on 2026-08-14.

### AI assistance

I used Claude Code to pull and classify the Buildkite history, draft the
changes, and run the replay. I reviewed every changed line and the
classification of every failing PR.

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

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Train] [Lightning] Smarter RayTrainReportCallback, e.g., autodetect DDP, custom checkpoint frequency

3 participants