Repository navigation
Add set_constraint method to Trial - #6754
Conversation
y0z
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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")
Since Lines 508 to 513 in 4267ccb |
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. |
|
The following updates were made to this PR:
|
| 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 |
There was a problem hiding this comment.
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_dictThen you can write this method like below:
| 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.
There was a problem hiding this comment.
Thank you. I have updated them according to your suggestion. PTAL.
c-bata
left a comment
There was a problem hiding this comment.
LGTM. Thank you for the update.
Motivation
This represents one of a series of changes aimed at providing official support for constrained optimization, following #6736. This PR introduces the
set_constraintmethod, elevating constrained optimization—previously implemented as a feature of samplers—to a core functionality within Optuna itself.Note: Deprecating
constraints_funcwill be done in the following PR.Description of the changes
set_constraintmethod toTrialset_constraintinstead ofconstraints_func