Skip to content

[tune] Keep Repeater's mean score when the last repeat errors - #67013

Open
vineethsaivs wants to merge 2 commits into
ray-project:masterfrom
vineethsaivs:fix/tune-repeater-error-flag
Open

vineethsaivs wants to merge 2 commits into
ray-project:masterfrom
vineethsaivs:fix/tune-repeater-error-flag

Conversation

@vineethsaivs

@vineethsaivs vineethsaivs commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Repeater forwards the error flag of whichever repeat reports last together with the group's mean score. Searchers that skip errored trials (BayesOptSearch, HyperOptSearch) then drop a valid mean, but only when the failed repeat happens to finish last.

Cause: Repeater.on_trial_complete passes the last report's **kwargs, including error, with the mean.
Fix: forward error only when the mean is NaN, i.e. no repeat produced a score.
Test: pytest test_searcher_utils.py -k repeat (test file copied out of the tree, ray 2.56.1 wheel with this repeater.py overlaid). New test_repeater_error_flag: 2 of 6 cases fail before (error=True with mean 2.0), 12 passed after; whole file 18 passed. ruff 0.8.4 and black 22.10.0 clean.

Not a duplicate: searched open and closed PRs and issues for "Repeater". #65960 (crash when search finishes) and #65952 (unknown trial IDs, closed) touch other paths; none covers the error flag.

Repeater forwarded the error flag of whichever repeat reported last
together with the mean score of the group. A searcher that skips errored
trials (BayesOptSearch, HyperOptSearch) then dropped a valid mean, and
only when the failed repeat happened to finish last. Forward the flag
only when no repeat produced a score.

Signed-off-by: Vineeth Sai <[email protected]>
@vineethsaivs
vineethsaivs requested a review from a team as a code owner October 14, 2026 16:49

@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 modifies the Repeater class in Ray Tune to ensure that the error flag is only passed to the wrapped searcher if all repeats failed, preventing the mean score of successful repeats from being discarded. A unit test has been added to verify this behavior. The review feedback recommends avoiding a RuntimeWarning: Mean of empty slice when all repeats fail by checking if all scores are NaN before calling np.nanmean().

Comment thread python/ray/tune/search/repeater.py Outdated

if trial_group.finished_reporting():
scores = trial_group.scores()
mean_score = np.nanmean(scores)

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

Using np.nanmean() on a slice or array containing only NaN values (which occurs when all repeats fail to produce a score) raises a RuntimeWarning: Mean of empty slice. To avoid cluttering the logs with this warning, we can check if all scores are NaN before calling np.nanmean().

Suggested change
mean_score = np.nanmean(scores)
mean_score = np.nan if np.isnan(scores).all() else np.nanmean(scores)

@ray-gardener ray-gardener Bot added tune Tune-related issues community-contribution Contributed by the community labels Oct 14, 2026

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

I independently verified the fix against parent e00c7f4b and PR HEAD 8ffddc46 using identical deterministic regression tests.

Four focused cases are RED on the parent and GREEN on the PR. They confirm that a failed repeat completing last no longer causes a valid aggregated score to be discarded.

I also verified the behavior through actual BayesOptSearch and HyperOptSearch state. The PR preserves the valid mean, while the parent either drops the result or marks the group as failed. Group completion still produces a single callback using the primary trial ID.

The all-NaN mixed-outcome case remains completion-order dependent on both revisions. I consider this an existing policy boundary, not a regression introduced by this PR.

No implementation correctness issue was found within the tested scope.

dstrodtman added a commit that referenced this pull request Oct 30, 2026
…67610)

## Summary

Adds the missing docstrings, `Args:` entries, and `Returns:` sections on
public Ray Tune symbols in `search`, `stopper`, `trainable`, `context`,
`utils`, `execution`, and `logger`. Each describes existing behavior,
written from the code. It follows #67608, which covers
`ray.tune.schedulers`.

Stacked on #67608: this PR targets that branch so the correctness PR
above it can build on both, and retargets to `master` once #67608
merges. The two PRs share no files.

## Before

Across these subpackages, 23 public symbols had no docstring, 43
parameters had no `Args:` entry, and 14 callables that annotate a return
type had no `Returns:` section. The sampling functions such as
`tune.uniform`, `tune.quniform`, and `tune.randint` described their
bounds in prose but had no `Args:` block.

## After

19 of the 23 docstrings, 35 of the 43 parameters, and 10 of the 14
`Returns:` sections are documented. Where a base class lacked the
docstring its overrides inherit, this PR documents the base instead of
each override: `Searcher.get_state`, `Searcher.set_state`,
`Stopper.__call__`, and `Stopper.stop_all`. That covers both
`ConcurrencyLimiter` classes and `Repeater`, and `CombinedStopper`.

Behavior is unchanged. The diff touches only docstrings, which the guard
below confirms.

## Not in this PR

- **Four methods with untyped signatures:**
`BasicVariantGenerator.set_state` and `save_to_dir`,
`FunctionStopper.is_valid_function`, and `Trainable.reset`. pydoclint,
run with `--arg-type-hints-in-signature`, rejects an `Args:` section on
a signature without type hints, so documenting these 6 parameters needs
a signature change. That signature change is in #67612, since this PR is
docstring-only. `BasicVariantGenerator.set_state` and
`FunctionStopper.is_valid_function` get a docstring here, without
sections.
- **`TuneContext.get_trial_name`, `get_trial_id`, `get_trial_resources`,
and `get_trial_dir`:** these take their docstrings at runtime from
`ray.train._internal.session` through `@_copy_doc`, so they render
documented already. A docstring written on the method would be
overwritten. Their `Returns:` sections belong on the `session`
functions, which Ray Train owns.
- **`Repeater.on_trial_complete`:** #67013 changes this method and edits
the same docstring, so its `Args:` entries are left to land after that
PR.

## For reviewers

These docstrings are worth a close read:

- `Verbosity` documents the four levels as the `verbose` argument of
`tune.run` describes the legacy output, and notes that the default
output treats levels 2 and 3 the same (`get_air_verbosity` in
`tune/experimental/output.py`).
- `PlacementGroupFactory.__call__` is deprecated. Its new docstring says
so and points to `to_placement_group()`.
- `BasicVariantGenerator.get_state` documents that it returns `False`
instead of a state when any variants are generated lazily.

## Duplicate check

No open PR documents these symbols. Open PRs #66923 (`stopper.py`),
#66699 (`logger/json.py`), and #58359 (`utils/util.py`) change code in
files this PR touches, and all three apply cleanly on top of this
branch. #67013 (`repeater.py`) also applies cleanly, because this PR
leaves the method it changes alone.

## Testing

- `python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base
upstream/master HEAD)"`: `docstring-only guard: 15 file(s), docstrings
only.`
- The full pre-commit suite on the changed files, including ruff, black,
pydoclint, and the docstyle hook: passed.
- `ci/ray_ci/doc/api_param_coverage.py`, run over `python/ray/tune/`
outside `schedulers/`: 43 undocumented parameters on `master`, 8 on this
branch: 6 on the four untyped signatures and 2 on
`Repeater.on_trial_complete`, all listed above.
- The commit carries an `@rtd-build` line, so the Read the Docs preview
renders the changed docstrings.

AI assistance (Claude Code) was used to prepare this 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]>
dstrodtman added a commit that referenced this pull request Oct 30, 2026
…umented (#67612)

## Summary

Adds type hints to four public Ray Tune methods so their parameters can
be documented, and documents them: `BasicVariantGenerator.set_state` and
`save_to_dir`, `FunctionStopper.is_valid_function`, and
`Trainable.reset`. It also corrects the `ExperimentPlateauStopper` error
message for `patience`.

Stacked on #67610, which writes the docstrings these `Args:` sections
extend. It retargets to `master` once #67610 and #67608 merge.

## Why this isn't in the docstring-only PRs

Ray's pydoclint hook runs with `--arg-type-hints-in-signature`, so it
rejects an `Args:` section on a signature without type hints. These four
methods had none, so documenting their 6 parameters needs a signature
change. A signature change isn't docstring-only, so it's in its own PR
without the `docstring-only` label, and premerge runs Tune's tests on
it.

## Changes

- `BasicVariantGenerator.set_state(self, state: Dict)`, with `Args:`.
- `BasicVariantGenerator.save_to_dir(self, dirpath: str, session_str:
str) -> Optional[bool]`, with a docstring, `Args:`, and `Returns:`. It
returns `False` when it skips saving because variants are generated
lazily, and otherwise `None`.
- `FunctionStopper.is_valid_function(cls, fn: Any) -> bool`, with
`Args:`, `Returns:`, and `Raises:`.
- `Trainable.reset(self, new_config: Dict, storage:
Optional[StorageContext] = None) -> bool`, with `Args:` and `Returns:`.
- `ExperimentPlateauStopper` raised `"Patience must be a strictly
positive integer."`, but the check is `patience < 0` and `patience`
defaults to `0`. The message now says "a non-negative integer." The
matching `Raises:` entry is corrected in #67611.

The type hints don't change behavior. Every name they use is already
imported at runtime in its module.

## Duplicate check

No open PR changes these signatures. #67013 changes `Repeater` in
`search/repeater.py`, which this PR doesn't touch. This branch merges
cleanly with #67611, its sibling on #67610.

## Testing

- The full pre-commit suite on the changed files, including ruff, black,
pydoclint, and the docstyle hook: passed.
- No test asserts the old `patience` error message (`grep -rn "Patience
must" python/ray`).
- Tune's unit tests run in premerge on this PR.

AI assistance (Claude Code) was used to prepare this 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]>
np.nanmean warns "Mean of empty slice" on an all-NaN input, which is
what a group of failed repeats produces. Return NaN directly in that
case, and make the error flag test fail on any RuntimeWarning.

Signed-off-by: Vineeth Sai <[email protected]>
@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Pushed 6676f99: an all-NaN score list now returns NaN without calling np.nanmean, so no RuntimeWarning, and the test fails on any RuntimeWarning. The mixed all-NaN completion-order case hikaru-212 noted is unchanged 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 Nov 20, 2026
@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Still relevant: the source file has not changed on master since this was opened, and it merges cleanly. Ready for a maintainer review.

@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 Nov 27, 2026

This branch has not been deployed

No deployments
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 tune Tune-related issues 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.

2 participants