Skip to content

[tune] Fix get_dataframe crashing on an all-NaN metric with pandas 3 - #67291

Merged
pseudo-rnd-thoughts merged 1 commit into
ray-project:masterfrom
mottopanikeiku:fix/tune-dataframe-all-nan-metric
Oct 29, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
ray-project:masterfrom
mottopanikeiku:fix/tune-dataframe-all-nan-metric

Conversation

@mottopanikeiku

Copy link
Copy Markdown
Contributor

Description

With pandas 3, Series.idxmax()/idxmin() raise ValueError: Encountered all NA values when every value is NaN (pandas 2 returned NaN with a FutureWarning). ExperimentAnalysis._retrieve_rows relied on the old behavior: the NaN index made df.iloc[idx] raise TypeError, which was caught to skip the trial with a warning (#9381). On pandas 3 the ValueError escapes, so ResultGrid.get_dataframe(filter_metric=..., filter_mode=...) and ExperimentAnalysis.dataframe(metric, mode) fail as soon as one trial only reported NaN for the metric, for example a run that diverged in its first epoch. Ray allows pandas >= 2.2.3, and a fresh install of ray[tune] currently gets pandas 3.1.0.

This PR checks for an all-NaN metric before calling idxmax/idxmin and skips that trial with the same warning as before. The TypeError fallback only handled that case, so it is removed.

import ray
from ray import tune

def f(config):
    for step in [3, 1, 2]:
        tune.report({"metric": float("nan") if config["diverged"] else step})

results = tune.Tuner(f, param_space={"diverged": tune.grid_search([False, True])}).fit()
results.get_dataframe(filter_metric="metric", filter_mode="min")
# pandas 3.1.0, before: ValueError: Encountered all NA values
# after: warning for the diverged trial, one row (diverged=False, metric=1)

Observed in a small learning-rate sweep (lr in {0.01, 0.1, 1000} on the scikit-learn diabetes data; lr=1000 reports NaN every epoch), calling get_dataframe(filter_metric="val_mse", filter_mode="min"):

pandas 2.3.3 pandas 3.1.0
before FutureWarning + warning, rows for lr=0.01 (0.552252) and lr=0.1 (0.548337) ValueError: Encountered all NA values
after warning, same two rows warning, same two rows

I found this by reading and testing the code.

Related issues

Related to #9364 and #9381 (the original NaN handling, which this restores on pandas 3).

Additional information

Not a duplicate: I searched issues and PRs for "Encountered all NA values", _retrieve_rows, idxmin/idxmax and NaN with get_dataframe, and checked the files changed by the open Tune PRs; none touch this code path.

Tests (test files from this branch, run against the Ray 2.59.0 wheel with this branch's experiment_analysis.py loaded on top; that file did not change between 2.59.0 and master):

  • python -m pytest -q test_result_grid.py
    • pandas 3.1.0 before the fix: 1 failed, 8 passed (test_result_grid_df_all_nan_metric - ValueError: Encountered all NA values)
    • pandas 3.1.0 after: 9 passed
    • pandas 2.3.3 (the CI pin): passes before and after, because the old fallback still works there
  • python -m pytest -q test_experiment_analysis.py after the fix, pandas 3.1.0: 33 passed
  • pre-commit hooks for the two files (ruff, black, pydoclint, check-ast, whitespace): passed

I made this PR and directed its development, with AI assistance from Claude and GPT-6 Astra.

With pandas 3, idxmax/idxmin raise instead of returning NaN when every value is NaN, so ResultGrid.get_dataframe(filter_metric=..., filter_mode=...) failed whenever one trial, such as a diverged run, only reported NaN for the metric. I skip such trials with the existing warning before calling idxmax/idxmin, which is what the TypeError fallback from ray-project#9381 did on pandas 2, and add a regression test.

Assisted-by: Claude
Assisted-by: GPT-6 Astra
Signed-off-by: mottopanikeiku <[email protected]>
@mottopanikeiku
mottopanikeiku requested a review from a team as a code owner October 22, 2026 16:51

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request handles cases where a trial diverged and only reported NaN values by checking if all metric values are NaN before calling idxmax() or idxmin(), preventing errors in pandas>=3. It also adds a test to verify this behavior. Feedback suggests retaining the removed try-except block around df.iloc[idx] to guard against potential TypeError exceptions when the DataFrame has non-integer index labels.

logger.warning(
"Warning: Non-numerical value(s) encountered for {}".format(path)
)
rows[path] = df.iloc[idx].to_dict()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Removing the try-except block around df.iloc[idx] reduces the robustness of the code. While idx is expected to be an integer under standard RangeIndex usage, if the DataFrame has non-integer index labels (e.g., strings or timestamps), idxmax() or idxmin() will return a non-integer label. Calling df.iloc[idx] with a non-integer will then raise a TypeError. Keeping the try-except block acts as a defensive guard against such unexpected index types or other edge cases.

            try:
                rows[path] = df.iloc[idx].to_dict()
            except TypeError:
                logger.warning(
                    "Warning: Non-numerical value(s) encountered for {}".format(path)
                )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the trial dataframes come from pd.json_normalize / pd.read_csv in _fetch_trial_dataframe, so they always have a RangeIndex and idx is a position here. the except TypeError only ever caught a NaN idx (its comment said so), and that case is now handled before idxmax/idxmin. keeping it would turn a real indexing bug into a misleading "non-numerical value" warning, so i left it out.

@ray-gardener ray-gardener Bot added tune Tune-related issues community-contribution Contributed by the community labels Oct 22, 2026

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, LGTM

@pseudo-rnd-thoughts pseudo-rnd-thoughts added the go add ONLY when ready to merge, run all tests label Oct 29, 2026
@pseudo-rnd-thoughts
pseudo-rnd-thoughts enabled auto-merge (squash) October 29, 2026 10:27
@mottopanikeiku

Copy link
Copy Markdown
Contributor Author

@pseudo-rnd-thoughts mark you maintain so many repos i contribute to i always get confused seeing your comments

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit 1fbe1eb into ray-project:master Oct 29, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests tune Tune-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants