Repository navigation
[tune] Add missing docstrings, Args, and Returns to the Tune schedulers - #67608
Conversation
Backfill Args entries, Returns sections, and missing docstrings on the public ray.tune.schedulers API. Each describes existing behavior. Most scheduler callbacks override TrialScheduler without a docstring of their own and inherit the base one, which had no Args or Returns. Document the TrialScheduler methods once instead of each override. Docstring-only: no code changes. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request improves the documentation of Ray Tune schedulers by adding detailed docstrings (including arguments and return values) to several scheduler classes, such as BOHB, HyperBand, Median Stopping Rule, PBT, Resource Changing, and the base Trial Scheduler. The review feedback points out a couple of minor inaccuracies in the newly added docstrings where the description does not perfectly match the implementation logic (specifically regarding mode-adjusted scores in PBT and strict inequality checks in the Median Stopping Rule).
| """Returns the last recorded score of each unfinished trial. | ||
|
|
||
| Args: | ||
| trials: The trials to read scores from. | ||
|
|
||
| Returns: | ||
| The last score of each trial in ``trials`` that has a score and | ||
| hasn't finished. | ||
| """ |
There was a problem hiding this comment.
The docstring for last_scores states that it returns the 'last recorded score' of each unfinished trial. However, the implementation actually returns the mode-adjusted score (multiplied by -1 if minimizing). It would be clearer to specify this in the docstring to avoid confusion for users or when writing unit tests.
| """Returns the last recorded score of each unfinished trial. | |
| Args: | |
| trials: The trials to read scores from. | |
| Returns: | |
| The last score of each trial in ``trials`` that has a score and | |
| hasn't finished. | |
| """ | |
| """Returns the last recorded mode-adjusted score of each unfinished trial. | |
| Args: | |
| trials: The trials to read scores from. | |
| Returns: | |
| The last mode-adjusted score of each trial in trials that has a | |
| score and hasn't finished. These scores are multiplied by -1 if the | |
| objective is being minimized. | |
| """ |
There was a problem hiding this comment.
Applied in ae2d144: the Returns: entry now says the scores are mode-adjusted, negated when mode is "min".
| ``TrialScheduler.PAUSE`` if at least ``min_time_slice`` has passed | ||
| since the trial last paused and other trials are waiting to run. |
There was a problem hiding this comment.
The docstring states that the trial is paused if 'at least' min_time_slice has passed. However, the code uses a strict inequality (time - self._last_pause[trial] > self._min_time_slice), meaning it requires strictly more than min_time_slice to have passed. Updating the docstring to say 'more than' instead of 'at least' makes it more accurate.
| ``TrialScheduler.PAUSE`` if at least ``min_time_slice`` has passed | |
| since the trial last paused and other trials are waiting to run. | |
| TrialScheduler.PAUSE if more than min_time_slice has passed | |
| since the trial last paused and other trials are waiting to run. |
There was a problem hiding this comment.
Applied in ae2d144: it now says "more than min_time_slice", matching the strict > in _on_insufficient_samples.
pseudo-rnd-thoughts
left a comment
There was a problem hiding this comment.
But why were these ever missing with pydocstring enabled?
PopulationBasedTraining.last_scores returns mode-adjusted scores, negated in min mode. MedianStoppingRule pauses only after more than min_time_slice, since the check is a strict inequality. Docstring-only: no code changes. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
Two gaps let them through. pydoclint checks that the sections a docstring has match the signature. It doesn't require a docstring at all, so a method with none passes, and Ray's ruff config doesn't enable the (Edited: an earlier version also blamed |
…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]>
## 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 off `master` would conflict with both. This PR retargets to `master` once they merge. ## Before and after **`HyperBandForBOHB.choose_trial_to_run`** (`schedulers/hb_bohb.py`) opened with "Fair scheduling within iteration by completion percentage," copied from `HyperBandScheduler`. `HyperBandScheduler` sorts brackets by `completion_percentage()`, but the BOHB override iterates them in creation order and returns the first ready trial. The next sentence said the trial list from `tune_controller` isn't used, but the override reads `tune_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 step `t`." The code compares against every other trial whose last result is at step `t` or later (`_trials_beyond_time`), whether or not it has completed, and each running average covers results from `grace_period` to `t` (`_running_mean`). **`tune.quniform`** (`search/sample.py`) gave `tune.uniform(1, 10)` as its example. It now uses `tune.quniform(1, 10, 0.5)` and says the value is rounded to a multiple of `0.5`, which is what `Quantized.sample` does. **`tune.randint`** (`search/sample.py`) gave `tune.randint(10)` as its example, but `upper` has no default, so that call raises a `TypeError`. It now uses `tune.randint(0, 10)`. **`Stopper`** (`stopper/stopper.py`) said "By default, this class does not stop any trials." The base `__call__` and `stop_all` raise `NotImplementedError`. The docstring now says so. **`ExperimentPlateauStopper`** (`stopper/experiment_plateau.py`) listed a `ValueError` when `patience` isn't "a strictly positive integer." The check is `patience < 0`, and `patience` defaults to `0`. The `Raises:` 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 from `SearchGenerator`. `BasicVariantGenerator` has no searcher or wrappers. It loads the newest checkpoint and calls `set_state`, and the summary now says that. **`tune.run` and `RunConfig`, `verbose`** (`tune/tune.py` and `air/config.py`) said that setting `RAY_AIR_NEW_OUTPUT=1` switches to the old verbosity levels. It's the reverse. `get_air_verbosity` in `tune/experimental/output.py` falls back to the old output only when the variable is `"0"`, and it defaults to `"1"`. Both docstrings now say `RAY_AIR_NEW_OUTPUT=0`. Behavior is unchanged. The diff touches only docstrings, which the guard below confirms. ## For reviewers If `HyperBandForBOHB` is 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.py` is owned by `@ray-project/ray-train`. It carries the same `RAY_AIR_NEW_OUTPUT` sentence as `tune.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 changes `CombinedStopper` code in `stopper.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.` - The full pre-commit suite on the changed files, including ruff, black, pydoclint, and the docstyle hook: passed. - 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]>
…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]>
Summary
Adds the missing docstrings,
Args:entries, andReturns:sections on the publicray.tune.schedulersAPI:FIFOScheduler,AsyncHyperBandScheduler,HyperBandScheduler,HyperBandForBOHB,MedianStoppingRule,PopulationBasedTraining,PopulationBasedTrainingReplay, andResourceChangingScheduler. Each describes existing behavior, written from the code. A follow-up PR covers the rest of the public Tune API.Before
On these schedulers, 5 public methods had no docstring, 85 parameters had no
Args:entry, and 23 methods that annotate a return type had noReturns:section.After
All of those are documented. Ray's
api_param_coverage.pyreports no undocumented parameters inpython/ray/tune/schedulers/. Most of the scheduler callbacks, such ason_trial_add,on_trial_result, andchoose_trial_to_run, overrideTrialSchedulerwithout a docstring of their own. Sphinx renders the base docstring for them, and that docstring had noArgs:orReturns:. So this PR documents theTrialSchedulermethods once instead of repeating the same entries on each override. Overrides that already had their own docstring, mostly inHyperBandSchedulerandHyperBandForBOHB, get their entries in place.Behavior is unchanged. The diff touches only docstrings, which the guard below confirms.
For reviewers
These are the docstrings worth a close read:
TrialScheduler.on_trial_resultnow documentsTrialScheduler.NOOPas a return value, for a scheduler that has already changed the trial's state itself.PopulationBasedTrainingandPopulationBasedTrainingReplayreturn it, andTuneControllertreats it as no action. The existing prose above it still lists onlyCONTINUE,PAUSE, andSTOP.HyperBandForBOHB.choose_trial_to_rundocumentsallow_recurse, and describes how the method processes brackets that have a paused trial when no trial is running.PopulationBasedTraining.reset_statsandlast_scorescarry a "Unit test only" comment but are public methods, so they now have docstrings.Two existing docstrings say something the code doesn't do. This PR leaves them as they are, since changing what a docstring asserts belongs in a separate correctness PR:
HyperBandForBOHB.choose_trial_to_runrepeats the "Fair scheduling within iteration by completion percentage" summary fromHyperBandScheduler, but it iterates brackets in creation order without sorting by completion.MedianStoppingRule.on_trial_resultsays it compares against "all completed trials". The code compares against every trial that has reported a result at or beyond the current step, whether or not it has completed.Duplicate check
No open PR documents these symbols. Open PRs #66710 and #67137 change code in
hyperband.py, and #58165, #59383, and #60646 change code inpbt.py. None of them edit the docstrings changed here, and #66710, #67137, and #58165 apply cleanly on top of this branch.Testing
python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base upstream/master HEAD)":docstring-only guard: 6 file(s), docstrings only.ci/ray_ci/doc/api_param_coverage.py, run overpython/ray/tune/schedulers/with a class index ofpython/ray/: 85 undocumented parameters onmaster, 0 on this branch.@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