Skip to content

Add float precision tests for storages - #6040

Merged
nabenabe0928 merged 12 commits into
optuna:masterfrom
not522:test-precision
Jun 4, 2025
Merged

nabenabe0928 merged 12 commits into
optuna:masterfrom
not522:test-precision

Conversation

@not522

@not522 not522 commented Apr 11, 2025

Copy link
Copy Markdown
Member

Motivation

To prevent float precision loss on the storage layer, this PR adds tests for float values.
Related to: #3227 #3327

Description of the changes

Adding precision tests on test_storages.py and test_with_server.py.

Overview of the implementation for the float precision

In the storage layer, the following methods must keep precision of values.

  • set_trial_state_values
  • set_trial_intermediate_value
  • set_trial_param
  • set_study_user_attr
  • set_study_system_attr
  • set_trial_user_attr
  • set_trial_system_attr

Note: Outside of the storage layer, to_internal_repr / to_external_repr of distributions must also keep precision. These are tested in test_distributions.py.

These methods handle the following floats:

  • set_trial_state_values
    • finite values / inf / -inf
  • set_trial_intermediate_value
    • finite values / inf / -inf / nan
  • set_trial_param
    • finite values (for FloatDistribution)
    • finite values / inf / -inf / nan (for CategoricalDistribution)
  • set_study_user_attr / set_study_system_attr / set_trial_user_attr / set_trial_system_attr
    • finite values / inf / -inf / nan

Storage classes

Note: We assume that there is no precision issues in the encoded JSON string https://docs.python.org/3.13/library/json.html#implementation-limitations.

InMemoryStorage

All values ​​are stored as Python variables so there are no precision issues.

JournalStorage

It dumps all the values ​​into JSON strings and saves them.

RDBStorage

All sqlalchemy.Float specify double-precision.

Note: MySQL cannot handle infinities.

  • set_trial_state_values
    • Values are saved as sqlalchemy.Float and TrialValueType.
  • set_trial_intermediate_value
    • Values are saved as sqlalchemy.Float and TrialIntermediateValueType.
  • set_trial_param
    • FloatDistribution
      • Parameters are saved as sqlalchemy.Float.
      • Distributions are saved as encoded JSON strings.
    • CategoricalDistribution
      • Indexes of parameters are saved as sqlalchemy.Float instead of values of them.
      • Distributions are saved as encoded JSON strings.
  • set_study_user_attr / set_study_system_attr / set_trial_user_attr / set_trial_system_attr
    • It dumps all the values ​​into JSON strings and saves them.

GrpcStorageProxy

The precision of values are specified in api.proto.

  • set_trial_state_values
    • Saved as double.
  • set_trial_intermediate_value
    • Saved as double.
  • set_trial_param
    • FloatDistribution
      • Saved as double.
    • CategoricalDistribution
      • Indexes are saved as doubles instead of values.
  • set_study_user_attr / set_study_system_attr / set_trial_user_attr / set_trial_system_attr
    • Saved as JSON strings.

@not522 not522 added the test Unit test. label Apr 11, 2025
@c-bata

c-bata commented Apr 14, 2025

Copy link
Copy Markdown
Member

@nabenabe0928 @sawa3030 @kAIto47802 Could you review this PR?

Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
@nabenabe0928

Copy link
Copy Markdown
Contributor

I looked into BaseStorage and confirmed that the following methods set values:

  • set_study_user_attr
  • set_study_system_attr
  • set_trial_param
  • set_trial_state_values
  • set_trial_intermediate_value
  • set_trial_user_attr
  • set_trial_system_attr

These coincide with the PR description.

Plus, I confirmed that the float values each method can receive are also correct in the PR description.

@nabenabe0928 nabenabe0928 Apr 15, 2025 •

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.

I will check each of them once I confirm their tests:

  • set_study_user_attr
  • set_study_system_attr
  • set_trial_param
  • set_trial_state_values
  • set_trial_intermediate_value
  • set_trial_user_attr
  • set_trial_system_attr

Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved

@nabenabe0928 nabenabe0928 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.

tests/storages_tests/test_storages.py looks good to me:)

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.

I will check each of them once I confirm their tests:

  • set_study_user_attr
  • set_study_system_attr
  • set_trial_param
  • set_trial_state_values
  • set_trial_intermediate_value
  • set_trial_user_attr
  • set_trial_system_attr

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.

Ok, I found out that this file requires exactly the same changes as test_storages.py.

@nabenabe0928 nabenabe0928 added this to the v4.4.0 milestone Apr 16, 2025
@not522

not522 commented Apr 16, 2025

Copy link
Copy Markdown
Member Author

Thank you. I updated this PR as you suggested. PTAL.

Comment thread tests/storages_tests/test_storages.py Outdated
# Test setting value.
for key, value in FLOAT_ATTRS.items():
storage.set_study_user_attr(study_id, key, value)
assert is_equal_floats(storage.get_study_user_attrs(study_id)[key], value)

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.

I thought this assertion is also ensured in the following line. Would you mind explaining why this additional check is necessary?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is just a copy from another test. I simplified it.

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.

Sorry for bringing this up again, but after reconsideration, I’m wondering if we really need is_equal_float_dicts. I believe we could replace is_equal_float_dicts with is_equal_floats. This would help keep the test pattern consistent throughout the PR and make it easier to follow.

Comment thread tests/storages_tests/test_storages.py Outdated
Comment on lines +601 to +617
for key, value in FLOAT_ATTRS.items():
if math.isnan(value): # NOTE: `suggest_float` does not generate `nan`.
continue
param_name = "float_" + key
float_dist = FloatDistribution(low=value, high=value)
internal_repr = float_dist.to_internal_repr(value)
storage.set_trial_param(trial_id, param_name, internal_repr, float_dist)
assert is_equal_floats(storage.get_trial_param(trial_id, param_name), internal_repr)
assert storage.get_trial(trial_id).distributions[param_name] == float_dist

for key, value in FLOAT_ATTRS.items():
param_name = "categorical_" + key
categorical_dist = CategoricalDistribution(choices=(value,))
internal_repr = categorical_dist.to_internal_repr(value)
storage.set_trial_param(trial_id, param_name, internal_repr, categorical_dist)
assert is_equal_floats(storage.get_trial_param(trial_id, param_name), internal_repr)
assert storage.get_trial(trial_id).distributions[param_name] == categorical_dist

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.

How about parameterizing the distribution type to simplify the code?

Comment on lines +49 to +52
for key, value in a.items():
if not is_equal_floats(value, b[key]):
False
return True

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.

Suggested change
for key, value in a.items():
if not is_equal_floats(value, b[key]):
False
return True
return all(is_equal_floats(value, b[key]) for key, value in a.items())

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.

Once this modification is applied, this PR looks good to me!

@sawa3030 sawa3030 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.

Thank you for all the updates. LGTM!

@github-actions

github-actions Bot commented May 1, 2025

Copy link
Copy Markdown
Contributor

This pull request has not seen any recent activity.

@github-actions github-actions Bot added the stale Exempt from stale bot labeling. label May 1, 2025
@nabenabe0928 nabenabe0928 removed the stale Exempt from stale bot labeling. label May 2, 2025

@kAIto47802 kAIto47802 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for your PR!
I've reviewed test_storages.py, leaving some comments. PTAL :octocat:

Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Resolved
Comment thread tests/storages_tests/test_storages.py Outdated
Comment on lines +596 to +597
# NOTE: suggest_float does not generate NaN.
if isinstance(distribution, FloatDistribution) and math.isnan(value):

@kAIto47802 kAIto47802 May 7, 2025 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

As you also mentioned in your PR comments:

  • set_trial_param
    • finite values (for FloatDistribution)

set_trial_param does not handle ±inf either.

Also, the usage of "NaN" vs. nan is inconsistent (cf. using nan in test_set_trial_state_values_for_floats).

Suggested change
# NOTE: suggest_float does not generate NaN.
if isinstance(distribution, FloatDistribution) and math.isnan(value):
# NOTE: `suggest_float` does not generate `nan` or `±inf`.
if isinstance(distribution, FloatDistribution) and not math.isfinite(value):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

On second thought, it seemed inappropriate to assume that suggest_float does not handle infinities. For example, the following sampler can handle infinities. What do you think?

import struct
import numpy as np
import optuna

class Sampler(optuna.samplers.BaseSampler):
    def infer_relative_search_space(self, study, trial):
        return {}

    def sample_relative(self, study, trial, search_space):
        return {}

    def float_to_int(self, value):
        return struct.unpack("q", struct.pack("d", value))[0]

    def int_to_float(self, value):
        return struct.unpack("d", struct.pack("q", value))[0]

    def sample_independent(self, study, trial, param_name, param_distribution):
        low = self.float_to_int(param_distribution.low)
        high = self.float_to_int(param_distribution.high)
        return self.int_to_float(np.random.randint(low, high + 1))

def objective(trial):
    return trial.suggest_float("x", 0, float("inf"))

study = optuna.create_study(sampler=Sampler())
study.optimize(objective, n_trials=10)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It may not be a specification that needs testing. In this PR, I changed to test only finite values.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I see. Thank you for the reply!

@kAIto47802 kAIto47802 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I've also reviewed test_with_server.py, leaving some comments. PTAL :octocat:

Note

All of my comments in test_with_server.py are the same as those in test_storages.py.

float_distribution = FloatDistribution(low=value, high=value)
categorical_distribution = CategoricalDistribution(choices=(value,))
for distribution in (float_distribution, categorical_distribution):
# NOTE: suggest_float does not generate NaN, and MySQL cannot handle infinities.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same as I mentioned in test_storages.py.

Suggested change
# NOTE: suggest_float does not generate NaN, and MySQL cannot handle infinities.
# NOTE: `suggest_float` does not generate `nan` or `±inf`, and MySQL cannot handle `±inf`.

@kAIto47802

kAIto47802 commented May 14, 2025 •

Copy link
Copy Markdown
Collaborator

I think using a fixture like this can significantly reduce the duplicate management of the float tests in test_storages.py and test_with_server.py.

@pytest.fixture(params=STORAGE_MODES + [None])
def storage_mode(request: pytest.FixtureRequest) -> Generator[BaseStorage, None, None]:
    if request.param is None:
        yield get_storage()
    else:
        with StorageSupplier(request.param) as storage:
            yield storage

However, this approach may not fit well with the current way the tests are split across files. We would likely need to either do all the float tests in test_storages.py or test_with_server.py, or create a new one specifically for tests that cover both cases.
What do you think--using a fixture like this or the current state?

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has not seen any recent activity.

@github-actions github-actions Bot added the stale Exempt from stale bot labeling. label May 22, 2025
@nabenabe0928 nabenabe0928 removed the stale Exempt from stale bot labeling. label May 22, 2025
@not522

not522 commented May 27, 2025

Copy link
Copy Markdown
Member Author

I unified implementations in test_storages.py and test_with_server.py. PTAL.

@github-actions

github-actions Bot commented Jun 3, 2025

Copy link
Copy Markdown
Contributor

This pull request has not seen any recent activity.

@github-actions github-actions Bot added the stale Exempt from stale bot labeling. label Jun 3, 2025
@kAIto47802 kAIto47802 removed the stale Exempt from stale bot labeling. label Jun 4, 2025

@kAIto47802 kAIto47802 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for your update! LGTM

Comment thread tests/storages_tests/test_storages.py Resolved
@nabenabe0928
nabenabe0928 enabled auto-merge June 4, 2025 07:36
@not522

not522 commented Jun 4, 2025

Copy link
Copy Markdown
Member Author

NOTE: suggest_float does not generate infinite values and NaN.

"infinite" is not the same as "infinity", and it generally includes NaN. So, how about just say "infinite values"?

@nabenabe0928

nabenabe0928 commented Jun 4, 2025 •

Copy link
Copy Markdown
Contributor

@not522

"infinite" is not the same as "infinity", and it generally includes NaN.

I am unsure if infinite includes NaN, as my knowledge, as do some developers, I believe.
IMO, I am leaning towards including the comment regarding NaN.

@not522

not522 commented Jun 4, 2025

Copy link
Copy Markdown
Member Author

It's a typical convention, for example, IEEE 754 or C's isfinite. But, writing it explicitly as the current code is OK, I think.

@nabenabe0928

Copy link
Copy Markdown
Contributor

@not522
Ok, then let me merge this PR for now:)

@nabenabe0928
nabenabe0928 merged commit be74654 into optuna:master Jun 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test Unit test.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants