Skip to content

Add set_constraint method to Trial - #6754

Merged
c-bata merged 6 commits into
optuna:masterfrom
not522:set-constraint
Jul 24, 2026
Merged

c-bata merged 6 commits into
optuna:masterfrom
not522:set-constraint

Conversation

@not522

@not522 not522 commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Motivation

This represents one of a series of changes aimed at providing official support for constrained optimization, following #6736. This PR introduces the set_constraint method, elevating constrained optimization—previously implemented as a feature of samplers—to a core functionality within Optuna itself.

Note: Deprecating constraints_func will be done in the following PR.

Description of the changes

  • Add set_constraint method to Trial
  • Replace tests and documentation to use set_constraint instead of constraints_func

@not522 not522 added this to the v5.0.0 milestone Jul 17, 2026
@not522 not522 added the feature Change that does not break compatibility, but affects the public interfaces. label Jul 17, 2026
@c-bata c-bata self-assigned this Jul 17, 2026
@y0z y0z self-assigned this Jul 17, 2026

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

When set_constraint() is called on a trial with old format constraints, both formats coexist:

# Before
system_attrs = {'constraints': [1.5, -0.5]}  # Old format

# After set_constraint("0", 10.0)
system_attrs = {
    'constraints': [1.5, -0.5],     # ← Still exists!
    'constraints:0': 10.0            # ← New format
}

# Results in inconsistent reads:
trial.constraints        # → {'0': 10.0, '1': -0.5}
constraints_func(trial)  # → [1.5, -0.5]

Although this rarely happens in actuality, it might be better to resolve this inconsistency.

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

I feel it a bit strange that we can overwrite the value of a constraint but cannot delete the constraint.
Have you considered the following approaches?

  • trial.set_constraint("c", None)
  • trial.remove_constraint("c")

@not522

not522 commented Jul 22, 2026

Copy link
Copy Markdown
Member Author

I feel it a bit strange that we can overwrite the value of a constraint but cannot delete the constraint.

Since report doesn't perform value updates, would it make sense for set_constraint to behave similarly?

if step in self._cached_frozen_trial.intermediate_values:
# Do nothing if already reported.
optuna_warn(
f"The reported value is ignored because this `{step=}` is already reported."
)
return

@y0z

y0z commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Since report doesn't perform value updates, would it make sense for set_constraint to behave similarly?

At least it looks more consistent. Furthermore, the immutability of constraint values ​​simplifies many implementations, although the impact of the resulting loss of flexibility is not immediately obvious.

@not522

not522 commented Jul 22, 2026 •

Copy link
Copy Markdown
Member Author

The following updates were made to this PR:

  • Prevented overriding constraint values
  • When both new and old format constraints exist, prioritize the new format constraints
  • Add validation for constraint values

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

LGTM

@y0z y0z removed their assignment Jul 24, 2026

@c-bata c-bata 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.

LGTM with a nit.

Comment thread optuna/trial/_fixed.py Outdated
Comment on lines +205 to +222
constraints_dict: dict[str, float] = {}

# Load constraints from old format (list)
con = self.system_attrs.get(_CONSTRAINTS_KEY)
if con is None:
return {}
return {str(i): c for i, c in enumerate(con)}
if con is not None:
for i, c in enumerate(con):
constraints_dict[str(i)] = c

# Load constraints from new format (individual keys)
prefix = f"{_CONSTRAINTS_KEY}:"
for key, value in self.system_attrs.items():
if key.startswith(prefix):
constraint_key = key[len(prefix) :]
if constraint_key in constraints_dict:
optuna_warn("Overwrite an old format constraint.")
constraints_dict[constraint_key] = value

return constraints_dict

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.

nit: It might be worth considering to introduce the following helper function in optuna/study/_constrained_optimization.py since this duplicated code exists in _fixed.py, _frozen.py, and _trial.py. What do you think?

def _get_constraints_from_system_attrs(system_attrs: dict[str, Any]) -> dict[str, float]:
        constraints_dict: dict[str, float] = {}

        # Load constraints from old format (list)
        con = system_attrs.get(_CONSTRAINTS_KEY)
        if con is not None:
            for i, c in enumerate(con):
                constraints_dict[str(i)] = c

        # Load constraints from new format (individual keys)
        prefix = f"{_CONSTRAINTS_KEY}:"
        for key, value in system_attrs.items():
            if key.startswith(prefix):
                constraint_key = key[len(prefix) :]
                if constraint_key in constraints_dict:
                    optuna_warn("Overwrite an old format constraint.")
                constraints_dict[constraint_key] = value
    return constraints_dict

Then you can write this method like below:

Suggested change
constraints_dict: dict[str, float] = {}
# Load constraints from old format (list)
con = self.system_attrs.get(_CONSTRAINTS_KEY)
if con is None:
return {}
return {str(i): c for i, c in enumerate(con)}
if con is not None:
for i, c in enumerate(con):
constraints_dict[str(i)] = c
# Load constraints from new format (individual keys)
prefix = f"{_CONSTRAINTS_KEY}:"
for key, value in self.system_attrs.items():
if key.startswith(prefix):
constraint_key = key[len(prefix) :]
if constraint_key in constraints_dict:
optuna_warn("Overwrite an old format constraint.")
constraints_dict[constraint_key] = value
return constraints_dict
return _get_constraints_from_system_attrs(self.system_attrs)

If you would prefer to merge this PR first, you can work on this in the future pull request.

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.

Thank you. I have updated them according to your suggestion. PTAL.

@c-bata c-bata 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.

LGTM. Thank you for the update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature Change that does not break compatibility, but affects the public interfaces.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants