Repository navigation
[tune] Type-annotate four Tune methods so their parameters can be documented - #67612
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves code documentation and type safety across several Ray Tune modules by adding type hints and detailed docstrings to methods like set_state, save_to_dir, is_valid_function, and reset. Additionally, it corrects an error message in experiment_plateau.py to accurately state that patience must be a non-negative integer. The review feedback suggests a minor improvement in trainable.py to use Dict[str, Any] instead of a bare Dict for the new_config parameter to ensure better type safety and consistency.
| return self._export_model(export_formats, export_dir) | ||
|
|
||
| def reset(self, new_config, storage=None): | ||
| def reset(self, new_config: Dict, storage: Optional[StorageContext] = None) -> bool: |
There was a problem hiding this comment.
For better type safety and consistency with other methods in this class (such as __init__ and default_resource_request), please specify the key and value types for new_config as Dict[str, Any] instead of the bare Dict.
| def reset(self, new_config: Dict, storage: Optional[StorageContext] = None) -> bool: | |
| def reset(self, new_config: Dict[str, Any], storage: Optional[StorageContext] = None) -> bool: |
There was a problem hiding this comment.
Applied in c0ec953, matching the config annotation on Trainable.__init__.
2f52d59 to
c8f9722
Compare
24d3c77 to
57318ca
Compare
c8f9722 to
f9d5d16
Compare
c0ec953 to
9808f31
Compare
…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 pydoclint runs with --arg-type-hints-in-signature, so it rejects an Args section on a signature without type hints. Add type hints to BasicVariantGenerator.set_state and save_to_dir, FunctionStopper.is_valid_function, and Trainable.reset, and document their parameters and return values. Also correct ExperimentPlateauStopper's error message: patience=0 is accepted and is the default, so patience must be non-negative, not strictly positive. The type hints don't change behavior. @rtd-build Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
Match the config annotation on Trainable.__init__. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
9808f31 to
f48c36c
Compare
Summary
Adds type hints to four public Ray Tune methods so their parameters can be documented, and documents them:
BasicVariantGenerator.set_stateandsave_to_dir,FunctionStopper.is_valid_function, andTrainable.reset. It also corrects theExperimentPlateauStoppererror message forpatience.Stacked on #67610, which writes the docstrings these
Args:sections extend. It retargets tomasteronce #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 anArgs: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 thedocstring-onlylabel, and premerge runs Tune's tests on it.Changes
BasicVariantGenerator.set_state(self, state: Dict), withArgs:.BasicVariantGenerator.save_to_dir(self, dirpath: str, session_str: str) -> Optional[bool], with a docstring,Args:, andReturns:. It returnsFalsewhen it skips saving because variants are generated lazily, and otherwiseNone.FunctionStopper.is_valid_function(cls, fn: Any) -> bool, withArgs:,Returns:, andRaises:.Trainable.reset(self, new_config: Dict, storage: Optional[StorageContext] = None) -> bool, withArgs:andReturns:.ExperimentPlateauStopperraised"Patience must be a strictly positive integer.", but the check ispatience < 0andpatiencedefaults to0. The message now says "a non-negative integer." The matchingRaises:entry is corrected in [tune] Correct Tune docstrings that contradict the code #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
Repeaterinsearch/repeater.py, which this PR doesn't touch. This branch merges cleanly with #67611, its sibling on #67610.Testing
patienceerror message (grep -rn "Patience must" python/ray).AI assistance (Claude Code) was used to prepare this PR.
🤖 Generated with Claude Code