Repository navigation
[tune] Add missing docstrings, Args, and Returns across the Tune API - #67610
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds and improves docstrings, including argument and return value descriptions, across various modules in Ray Tune to enhance documentation clarity. The feedback points out an inaccuracy in the docstring for BasicVariantGenerator.restore_from_dir, which incorrectly claims to restore searchers and search wrappers when it only restores the generator's own state.
| """Restores self + searcher + search wrappers from dirpath. | ||
|
|
||
| Args: | ||
| dirpath: Directory that holds the checkpoint file to restore from. | ||
| """ |
There was a problem hiding this comment.
The docstring for restore_from_dir states that it "Restores self + searcher + search wrappers from dirpath." However, BasicVariantGenerator is a basic variant generator that does not wrap or manage any searcher or search wrappers. It only restores its own state.\n\nUpdating this description to accurately reflect that it only restores the generator's state will improve code maintainability and prevent developer confusion.
"""Restores the generator's state from dirpath.\n\n Args:\n dirpath: Directory that holds the checkpoint file to restore from.\n """There was a problem hiding this comment.
Agreed. This PR is docstring-only and adds sections without changing what existing docstrings assert, so the summary fix is in the stacked correctness PR, #67611: "Restores the generator's state from the newest checkpoint in dirpath."
2f52d59 to
c8f9722
Compare
Backfill docstrings, Args entries, and Returns sections on public Ray Tune symbols in search, stopper, trainable, context, utils, execution, and logger. Each describes existing behavior. Searcher.get_state and set_state, and Stopper.__call__ and stop_all, are documented on the base class so the overrides that inherit them render the entries too. Docstring-only: no code changes. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
c8f9722 to
f9d5d16
Compare
## 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 public Ray Tune symbols insearch,stopper,trainable,context,utils,execution, andlogger. Each describes existing behavior, written from the code. It follows #67608, which coversray.tune.schedulers.Stacked on #67608: this PR targets that branch so the correctness PR above it can build on both, and retargets to
masteronce #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 noReturns:section. The sampling functions such astune.uniform,tune.quniform, andtune.randintdescribed their bounds in prose but had noArgs: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__, andStopper.stop_all. That covers bothConcurrencyLimiterclasses andRepeater, andCombinedStopper.Behavior is unchanged. The diff touches only docstrings, which the guard below confirms.
Not in this PR
BasicVariantGenerator.set_stateandsave_to_dir,FunctionStopper.is_valid_function, andTrainable.reset. pydoclint, run with--arg-type-hints-in-signature, rejects anArgs:section on a signature without type hints, so documenting these 6 parameters needs a signature change. That signature change is in [tune] Type-annotate four Tune methods so their parameters can be documented #67612, since this PR is docstring-only.BasicVariantGenerator.set_stateandFunctionStopper.is_valid_functionget a docstring here, without sections.TuneContext.get_trial_name,get_trial_id,get_trial_resources, andget_trial_dir: these take their docstrings at runtime fromray.train._internal.sessionthrough@_copy_doc, so they render documented already. A docstring written on the method would be overwritten. TheirReturns:sections belong on thesessionfunctions, which Ray Train owns.Repeater.on_trial_complete: [tune] Keep Repeater's mean score when the last repeat errors #67013 changes this method and edits the same docstring, so itsArgs:entries are left to land after that PR.For reviewers
These docstrings are worth a close read:
Verbositydocuments the four levels as theverboseargument oftune.rundescribes the legacy output, and notes that the default output treats levels 2 and 3 the same (get_air_verbosityintune/experimental/output.py).PlacementGroupFactory.__call__is deprecated. Its new docstring says so and points toto_placement_group().BasicVariantGenerator.get_statedocuments that it returnsFalseinstead 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.ci/ray_ci/doc/api_param_coverage.py, run overpython/ray/tune/outsideschedulers/: 43 undocumented parameters onmaster, 8 on this branch: 6 on the four untyped signatures and 2 onRepeater.on_trial_complete, all listed above.@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