Repository navigation
[tune] Correct Tune docstrings that contradict the code - #67611
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
Code Review
This pull request focuses on improving and correcting documentation across Ray Air and Ray Tune. Key updates include correcting the environment variable reference for legacy verbosity settings to RAY_AIR_NEW_OUTPUT=0, clarifying trial selection logic in BOHB, explaining the median stopping rule calculations, correcting sampling function examples for quniform and randint, and updating stopper documentation. There are no review comments, so I have no feedback to provide.
dstrodtman
force-pushed
the
doc-1922-tune-docstring-corrections
branch
from
October 30, 2026 15:23
da140d0 to
b8093e6
Compare
dstrodtman
force-pushed
the
doc-1922-tune-docstring-corrections
branch
from
October 30, 2026 16:21
b8093e6 to
a7ece3f
Compare
Fix eight docstring claims that the code doesn't match: - HyperBandForBOHB.choose_trial_to_run returns the first ready trial in bracket creation order. It doesn't sort by completion percentage, and it does read tune_controller. - MedianStoppingRule.on_trial_result compares against every other trial that has reached the current step, not only completed ones, averaged from grace_period onward. - The quniform example called tune.uniform, and the randint example called tune.randint(10), which has no default upper bound. - Stopper's base methods raise NotImplementedError. They don't default to never stopping. - ExperimentPlateauStopper accepts patience=0, its default. - BasicVariantGenerator.restore_from_dir restores only the generator. It has no searcher or wrappers. - RAY_AIR_NEW_OUTPUT=0, not 1, selects the legacy verbosity levels, in both tune.run and RunConfig. Docstring-only: no code changes. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
Define t as the result's time_attr value before using it, then state the comparison in order: which trials take part, what window their averages cover, and when the rule stops the trial. The claims are unchanged from the previous commit. Docstring-only: no code changes. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
dstrodtman
force-pushed
the
doc-1922-tune-docstring-corrections
branch
from
October 30, 2026 16:39
060966f to
c7642ab
Compare
pseudo-rnd-thoughts
approved these changes
Oct 30, 2026
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]>
dstrodtman
added a commit
that referenced
this pull request
Nov 3, 2026
## Description
This PR changes what three Tune docstring examples check, and corrects
defects that converting them exposed. It needs review from Tune
maintainers. It isn't a syntax-only conversion.
The `Callback`, `ResultGrid`, and `ResultGrid.get_dataframe` examples
were `.. testcode::` blocks, which griffe and MkDocs don't render. Each
was paired with a hidden `testoutput` whose body was only `...`, which
matches any output, so the doctest ran the code but checked nothing it
printed. This PR converts them to `>>>` doctests that show their output,
and makes these corrections:
**`ResultGrid` class example**
- **Removes the `try`/`except ValueError` around `tuner.fit()`.** It
never fires. A trial that raises is recorded in the result grid and
doesn't propagate out of `fit()`, as the "Failure handling" paragraph of
`Tuner.fit`'s docstring says. In a run of this example, `fit()` returned
normally with 5 of 10 trials errored. If `fit()` had raised, the loop
that follows would have failed with a `NameError` on `result_grid`.
- **Adds the missing space in the success message.** The two f-strings
concatenated to `with metrics{'loss': 0.0, ...}`.
- **Passes `filter_metric` and `filter_mode` to `get_dataframe`.** The
example passed `metric=` and `mode=`, which `get_dataframe` doesn't
accept. The line is `+SKIP`, so nothing caught the `TypeError`.
- Normalizes the over-indented `print` calls in the loop to four spaces.
**`Callback` class docstring**
- **Replaces the two `TrialRunner` references.** Tune no longer has a
`TrialRunner` class. Callbacks are passed through
`RunConfig(callbacks=...)`, as the example itself does, and
`TuneController` calls them
(`python/ray/tune/execution/tune_controller.py`).
- The example now shows its `Got result: 0` through `Got result: 9`
lines.
**`Tuner.fit` docstring**
- **Corrects the `Raises` section.** It said `fit()` raises
`RayTaskError` whenever the trainable raises, which contradicts the same
docstring's "Failure handling" paragraph.
`TuneController._trial_task_failure` re-raises a trial's exception only
when `fail_fast` is `"raise"`, and otherwise logs it and records it on
the trial. I ran a trainable that raises `ValueError` under each
`FailureConfig(fail_fast=...)` setting. With `False` and `True`, `fit()`
returned a `ResultGrid` with `num_errors == 1`. With `"raise"`, it
raised `RayTaskError(ValueError)`, which is also a `ValueError`. That's
probably where the `ResultGrid` example's `except ValueError` came from.
**How the output is matched.** Tune prints its progress tables to
stdout, which a stock doctest compares. The examples use the pattern
`python/ray/tune/stopper/stopper.py` already uses: `print("[ignore]");
result_grid = tuner.fit() # doctest: +ELLIPSIS`, with `[ignore]...` as
the expected output. In the `Callback` example, the expected output is
`[ignore]...`, then `Got result: 0`, `...`, `Got result: 9`, and `...`,
so the callback's own lines are still checked. The `ResultGrid`
example's trainable fails at random, so its loop's expected output is
`Trial ...`.
**For reviewers**
- Is the `[ignore]` pattern acceptable in rendered API reference, or
would you prefer `RunConfig(verbose=0)` in these examples? That changes
the example code, so I didn't make it here.
- The `ResultGrid` example fails half its trials at random, so its
printed output can't be pinned down. It could fail trials based on the
config instead, so the output is deterministic. I kept the example's
behavior.
## Related issues
Related to #66748, which converted `Callback`'s method examples and left
this class example, and to #67619, the syntax-only conversion of Tune's
remaining never-run examples.
## Additional information
**Not a duplicate.** I searched open PRs for Tune doctest and `testcode`
changes. None touches these docstrings. #67611, which has merged,
corrected other Tune docstrings.
**Tests run**
These ran in a Python 3.12 virtualenv with `ray[tune]==2.59.0`, with
this branch's `callback.py` and `result_grid.py` copied over the
installed ones. The installed files differ from `master` only in
docstrings.
- `pytest --doctest-modules -p default_doctest_pytest_plugin` on both
files, using `bazel/default_doctest_pytest_plugin.py`, the way
`//python/ray/tune:py_doctest[tune]` runs them: 4 passed and 1 skipped,
three runs in a row. The skip is `get_best_result`'s existing `+SKIP`
example.
- To confirm the `Callback` example checks the callback's output, I
changed the expected `Got result: 9` to `Got result: 99`. The doctest
failed.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3
file(s), docstrings only."
- `pre-commit run --files` on all three files: all hooks pass.
The PR carries the `docstring-only` label, and its commit carries an
`@rtd-build` line for the Read the Docs preview.
AI assistance (Claude Code) was used for 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]>
Open
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Corrects eight Ray Tune docstrings that describe behavior the code doesn't have. This is a correctness change: it changes what the docstrings assert, so each item needs a technical read rather than a skim. The items surfaced while backfilling docstrings in #67608 and #67610.
Stacked on #67610, which is stacked on #67608. Several corrected lines sit right next to
Args:blocks those PRs add, so a branch offmasterwould conflict with both. This PR retargets tomasteronce they merge.Before and after
HyperBandForBOHB.choose_trial_to_run(schedulers/hb_bohb.py) opened with "Fair scheduling within iteration by completion percentage," copied fromHyperBandScheduler.HyperBandSchedulersorts brackets bycompletion_percentage(), but the BOHB override iterates them in creation order and returns the first ready trial. The next sentence said the trial list fromtune_controllerisn't used, but the override readstune_controller.get_trials()to check whether any trial is running. Both sentences now describe the override.MedianStoppingRule.on_trial_result(schedulers/median_stopping_rule.py) said it compares a trial against "the running averages of all completed trials' objectives reported up to stept." The code compares against every other trial whose last result is at steptor later (_trials_beyond_time), whether or not it has completed, and each running average covers results fromgrace_periodtot(_running_mean).tune.quniform(search/sample.py) gavetune.uniform(1, 10)as its example. It now usestune.quniform(1, 10, 0.5)and says the value is rounded to a multiple of0.5, which is whatQuantized.sampledoes.tune.randint(search/sample.py) gavetune.randint(10)as its example, butupperhas no default, so that call raises aTypeError. It now usestune.randint(0, 10).Stopper(stopper/stopper.py) said "By default, this class does not stop any trials." The base__call__andstop_allraiseNotImplementedError. The docstring now says so.ExperimentPlateauStopper(stopper/experiment_plateau.py) listed aValueErrorwhenpatienceisn't "a strictly positive integer." The check ispatience < 0, andpatiencedefaults to0. TheRaises:entry now says "a non-negative integer." The runtime error message says "strictly positive" too, but it's a code string, so it changes in #67612.BasicVariantGenerator.restore_from_dir(search/basic_variant.py) said it "Restores self + searcher + search wrappers," copied fromSearchGenerator.BasicVariantGeneratorhas no searcher or wrappers. It loads the newest checkpoint and callsset_state, and the summary now says that.tune.runandRunConfig,verbose(tune/tune.pyandair/config.py) said that settingRAY_AIR_NEW_OUTPUT=1switches to the old verbosity levels. It's the reverse.get_air_verbosityintune/experimental/output.pyfalls back to the old output only when the variable is"0", and it defaults to"1". Both docstrings now sayRAY_AIR_NEW_OUTPUT=0.Behavior is unchanged. The diff touches only docstrings, which the guard below confirms.
For reviewers
If
HyperBandForBOHBis meant to schedule by completion percentage like its parent, the bug is in the code rather than the docstring. Say so and I'll drop that item in favor of a code fix. The override's comments mark it as BOHB-specific ("MAIN CHANGE HERE"), but none of them explain the ordering.air/config.pyis owned by@ray-project/ray-train. It carries the sameRAY_AIR_NEW_OUTPUTsentence astune.py, so both get the same fix here.Duplicate check
No open PR edits these docstrings. Open PRs #66710 and #67137 change code in
hyperband.py, and #66923 changesCombinedStoppercode instopper.py. None of them touch the lines changed here.Testing
python ci/ray_ci/doc/check_docstring_only.py --base doc-1922-tune-api-docstrings:docstring-only guard: 8 file(s), docstrings only.@rtd-buildline, so the Read the Docs preview renders the changed docstrings.AI assistance (Claude Code) was used to prepare this PR.
🤖 Generated with Claude Code