Repository navigation
[tune] Rank a NaN metric last in HyperBand successive halving - #67137
vineethsaivs wants to merge 1 commit into
Conversation
sorted() with a NaN key has no consistent order, so one trial reporting NaN could keep itself and drop the best trial. Rank NaN worst so it is halved away. HyperBandForBOHB shares the bracket code. Signed-off-by: Vineeth Sai <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request updates the HyperBand scheduler's successive halving logic to handle NaN metric values gracefully by ranking them as worst (-np.inf) during sorting, preventing corruption of the sort order. It also adds a comprehensive unit test to verify this behavior. The review feedback suggests a robust improvement to handle potential KeyError or TypeError exceptions when accessing the trial metrics, ensuring the scheduler does not crash if a metric is missing or null.
| def score(trial: Trial) -> float: | ||
| # NaN compares false against everything, so it would corrupt the sort. | ||
| # Rank it worst, so a trial with a NaN metric is halved away. | ||
| value = metric_op * self._live_trials[trial][metric] | ||
| return -np.inf if np.isnan(value) else value |
There was a problem hiding this comment.
The score function directly accesses self._live_trials[trial][metric] and performs multiplication. If a trial's reported result is None, or if the metric key is missing from the result dictionary (which can happen if a trial fails to report the metric or under certain error conditions), this will raise a TypeError or KeyError and crash the entire tuning run.
Using a try-except block to catch KeyError and TypeError ensures defensive programming and robustness against malformed or missing metrics, safely ranking them as worst (-np.inf) instead of crashing.
| def score(trial: Trial) -> float: | |
| # NaN compares false against everything, so it would corrupt the sort. | |
| # Rank it worst, so a trial with a NaN metric is halved away. | |
| value = metric_op * self._live_trials[trial][metric] | |
| return -np.inf if np.isnan(value) else value | |
| def score(trial: Trial) -> float: | |
| # NaN compares false against everything, so it would corrupt the sort. | |
| # Rank it worst, so a trial with a NaN metric is halved away. | |
| try: | |
| value = metric_op * self._live_trials[trial][metric] | |
| return -np.inf if np.isnan(value) else value | |
| except (KeyError, TypeError): | |
| return -np.inf |
There was a problem hiding this comment.
Not changing: this PR only ranks NaN last, a missing or None metric is a separate existing case, and a blanket try/except would hide it.
hikaru-212
left a comment
There was a problem hiding this comment.
I independently verified the HyperBand NaN-ranking fix against merge-base 255cf353c4 and PR HEAD c5ca3ad33e, using revision-specific Tune source snapshots.
Beyond the PR's existing 3-to-1 regression, I tested two additional 4-to-2 successive-halving scenarios across all 24 trial-order permutations in both max and min modes:
[NaN, 0, 1, 2]: The baseline retained the wrong survivor set in 16/24 permutations per mode; HEAD correctly retained{1, 2}in all 24.[NaN_A, NaN_B, 0, +inf]: The baseline failed in 20/24 permutations per mode; HEAD correctly retained{0, +inf}in all 24.
Finite-score tie controls and the worst-direction infinity/NaN tie case remained unchanged. All 320 bracket executions passed the partition, capacity, metric-preservation, and rung-state invariant checks.
The verification used Python 3.12.3 and NumPy 2.2.6, with Ray 2.58.0 supplying non-Tune/native dependencies. The evidence is limited to the tested production bracket operations; it does not establish full Tune controller or BOHB integration behavior.
No additional correctness issue was found within the tested scope.
One separate policy question:
If every trial in a rung reports NaN, all ranking keys become -inf. Since Python's sort is stable and the implementation retains sorted_trials[-k:], the last k trials in the bracket's insertion order would be selected.
Is this insertion-order tie behavior intentional when an entire rung reports NaN, or should that case be handled under a separate scheduling policy?
I haven't independently tested this all-NaN case, and I don't consider it a regression introduced by this PR.
|
Not intentional policy: when a whole rung is NaN the keys tie at -inf, so the stable sort keeps the last k in insertion order, same as any other equal scores. That order was already arbitrary before this change, and I left a separate all-NaN rule out of scope. |
…rs (#67608) ## Summary Adds the missing docstrings, `Args:` entries, and `Returns:` sections on the public `ray.tune.schedulers` API: `FIFOScheduler`, `AsyncHyperBandScheduler`, `HyperBandScheduler`, `HyperBandForBOHB`, `MedianStoppingRule`, `PopulationBasedTraining`, `PopulationBasedTrainingReplay`, and `ResourceChangingScheduler`. 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 no `Returns:` section. ## After All of those are documented. Ray's `api_param_coverage.py` reports no undocumented parameters in `python/ray/tune/schedulers/`. Most of the scheduler callbacks, such as `on_trial_add`, `on_trial_result`, and `choose_trial_to_run`, override `TrialScheduler` without a docstring of their own. Sphinx renders the base docstring for them, and that docstring had no `Args:` or `Returns:`. So this PR documents the `TrialScheduler` methods once instead of repeating the same entries on each override. Overrides that already had their own docstring, mostly in `HyperBandScheduler` and `HyperBandForBOHB`, 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_result` now documents `TrialScheduler.NOOP` as a return value, for a scheduler that has already changed the trial's state itself. `PopulationBasedTraining` and `PopulationBasedTrainingReplay` return it, and `TuneController` treats it as no action. The existing prose above it still lists only `CONTINUE`, `PAUSE`, and `STOP`. - `HyperBandForBOHB.choose_trial_to_run` documents `allow_recurse`, and describes how the method processes brackets that have a paused trial when no trial is running. - `PopulationBasedTraining.reset_stats` and `last_scores` carry 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_run` repeats the "Fair scheduling within iteration by completion percentage" summary from `HyperBandScheduler`, but it iterates brackets in creation order without sorting by completion. - `MedianStoppingRule.on_trial_result` says 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 in `pbt.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.` - 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/schedulers/` with a class index of `python/ray/`: 85 undocumented parameters on `master`, 0 on this branch. - 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]>
|
Friendly ping in case this slipped through, happy to adjust anything if someone has a moment to look. |
|
This pull request has been automatically marked as stale because it has not had 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. |
HyperBand's successive halving sorted trials with a NaN key in the list. NaN has no consistent order, so a trial reporting NaN could be kept while the best trial was stopped. NaN is now ranked worst and halved away.
HyperBandForBOHBshares the bracket code.Not a duplicate: searched ray-project/ray PRs and issues for hyperband, successive_halving and NaN; none cover this. #66710 edits nearby lines of
successive_halving(rung sizes), not the ranking.Tests: copied
test_trial_scheduler.pyto a scratch dir and ran it against ray 2.56.1 with master'shyperband.pyoverlaid:python -m pytest test_trial_scheduler.py --noconftest -k "Hyperband or HyperBand or BOHB or Halving". New testtestSuccessiveHalvingRanksNanLastfails before (6 of 12 orderings keep the wrong trial) and passes after. 42 passed after; 2 BOHB tests fail before and after because HpBandSter is not installed.blackclean.