Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion ax/adapter/tests/test_torch_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@
from ax.utils.testing.mock import mock_botorch_optimize
from ax.utils.testing.preference_stubs import get_pbo_experiment
from botorch.acquisition import LearnedObjective
from botorch.acquisition.logei import qLogNoisyExpectedImprovement
from botorch.acquisition.logei import (
qLogNoisyExpectedImprovement,
qLogProbabilityOfFeasibility,
)
from botorch.acquisition.preference import (
AnalyticExpectedUtilityOfBestOption,
qExpectedUtilityOfBestOption,
Expand Down Expand Up @@ -1723,6 +1726,55 @@ def test_plbo_with_learned_objective_and_extra_metrics(self) -> None:
else:
self.assertEqual(acqf_model.num_outputs, 2)

@mock_botorch_optimize
def test_plbo_with_outcome_constraints(self) -> None:
"""Use the constraint-only metric for feasibility, not for utility."""
generator = BoTorchGenerator()
adapter = TorchAdapter(
experiment=self.exp,
data=self.exp.lookup_data(),
generator=generator,
)
# The fixture's metric1 observations are near 1000.
for bound, expected_acqf in (
(1100.0, qLogNoisyExpectedImprovement),
(900.0, qLogProbabilityOfFeasibility),
):
with self.subTest(bound=bound):
config = self.pref_opt_config.clone_with_args(
outcome_constraints=[
OutcomeConstraint(
expression=f"metric1 <= {bound}",
metric_name_to_signature={
"metric1": self.exp.get_metric("metric1").signature
},
)
]
)
gen_run = adapter.gen(n=1, optimization_config=config)
self.assertEqual(len(gen_run.arms), 1)

acquisition = none_throws(generator._acquisition)
self.assertIsInstance(acquisition.acqf, expected_acqf)
self.assertEqual(acquisition.acqf.model.num_outputs, 3)
self.assertIsNone(acquisition.objective_thresholds)
if isinstance(
acqf := acquisition.acqf,
(qLogNoisyExpectedImprovement, qLogProbabilityOfFeasibility),
):
constraint_fns = none_throws(acqf._constraints)
else:
self.fail(f"Unexpected acquisition function: {type(acqf)}")
self.assertEqual(len(constraint_fns), 1)
samples = torch.tensor(
[[bound - 1, 0.0, 0.0], [bound + 1, 0.0, 0.0]],
dtype=torch.double,
)
torch.testing.assert_close(
constraint_fns[0](samples),
torch.tensor([-1.0, 1.0], dtype=torch.double),
)

@mock_botorch_optimize
def test_plbo_validation_fails_with_allowed_and_disallowed_transform(self) -> None:
"""Validation fails/passes when using disallowed/allowed transforms."""
Expand Down
9 changes: 1 addition & 8 deletions ax/core/optimization_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ def __init__(
preference profile for the experiment. An auxiliary experiment with
this name and purpose PE_EXPERIMENT should be attached to
the experiment.
outcome_constraints: Constraints on metrics. Not yet supported.
outcome_constraints: Constraints on metrics.
expect_relativized_outcomes: Whether the learned objective expects outcomes
in relative percentage scale (e.g., -1 means -1% change vs. status quo)
after transforms. When True, TorchAdapter validates that a
Expand All @@ -558,13 +558,6 @@ def __init__(
"Use `OptimizationConfig` instead if using a "
"single-metric objective."
)
if outcome_constraints:
raise NotImplementedError(
"Outcome constraints are not yet supported in "
"PreferenceOptimizationConfig"
)

# Call parent's __init__ with objective_thresholds=None
super().__init__(
objective=objective,
outcome_constraints=outcome_constraints,
Expand Down
46 changes: 29 additions & 17 deletions ax/core/tests/test_optimization_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,23 +651,35 @@ def test_Init(self) -> None:
self.assertEqual(config.objective, self.multi_objective)
self.assertEqual(config.outcome_constraints, [])

# Test that outcome_constraints are not supported
with self.assertRaisesRegex(
NotImplementedError, "Outcome constraints are not yet supported"
):
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
PreferenceOptimizationConfig(
objective=self.multi_objective,
preference_profile_name=self.preference_profile_name,
outcome_constraints=[
OutcomeConstraint(
metric=self.metrics["metric1"],
op=ComparisonOp.LEQ,
bound=0.5,
)
],
)
constraints = [
OutcomeConstraint(
expression="metric1 <= 0.5",
metric_name_to_signature={"metric1": self.metrics["metric1"].signature},
)
]
constrained = PreferenceOptimizationConfig(
objective=self.multi_objective,
preference_profile_name=self.preference_profile_name,
outcome_constraints=constraints,
)
self.assertEqual(constrained.outcome_constraints, constraints)
self.assertEqual(constrained.all_constraints, constraints)
self.assertEqual(constrained.objective_thresholds, [])

cloned = assert_is_instance(constrained.clone(), PreferenceOptimizationConfig)
self.assertEqual(cloned.outcome_constraints, constraints)
self.assertIsNot(cloned.outcome_constraints[0], constraints[0])
self.assertEqual(
constrained.clone_with_args(outcome_constraints=None).outcome_constraints,
[],
)

with self.assertRaisesRegex(ValueError, "Duplicate outcome constraints"):
PreferenceOptimizationConfig(
objective=self.multi_objective,
preference_profile_name=self.preference_profile_name,
outcome_constraints=constraints * 2,
)

def test_Eq(self) -> None:
config1 = PreferenceOptimizationConfig(
Expand Down
1 change: 1 addition & 0 deletions ax/generators/torch/botorch_modular/acquisition.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ def _update_objective_thresholds(self, torch_opt_config: TorchOptConfig) -> None
"""
if not (
torch_opt_config.is_moo
and not torch_opt_config.use_learned_objective
and (
self._objective_thresholds is None
or self._objective_thresholds.isnan().any()
Expand Down
12 changes: 11 additions & 1 deletion ax/generators/torch/botorch_modular/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,10 +563,20 @@ def _instantiate_acquisition(
self._user_specified_botorch_acqf_class is None
and self._botorch_acqf_classes_with_options is None
):
datasets = self.surrogate.training_data
if torch_opt_config.use_learned_objective:
# The auxiliary preference data lives in outcome space, not in the
# search space used to check feasibility of observed designs.
outcome_names = set(self.surrogate.outcomes)
datasets = [
dataset
for dataset in datasets
if outcome_names.issuperset(dataset.outcome_names)
]
self._botorch_acqf_class = choose_botorch_acqf_class(
search_space_digest=search_space_digest,
torch_opt_config=torch_opt_config,
datasets=self.surrogate.training_data,
datasets=datasets,
use_p_feasible=self.use_p_feasible,
)
return self.acquisition_class(
Expand Down
32 changes: 29 additions & 3 deletions ax/generators/torch/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,21 @@ def extract_objectives(
)


class _SubsetLearnedObjective(LearnedObjective):
"""Evaluate learned utility on the objective columns of the posterior samples."""

def __init__(self, pref_model: Model, outcome_indices: Tensor) -> None:
super().__init__(pref_model=pref_model)
self._outcome_indices: Tensor
self.register_buffer("_outcome_indices", outcome_indices)

def forward(self, samples: Tensor, X: Tensor | None = None) -> Tensor:
"""Keep constraint-only columns out of the preference model's input."""
return super().forward(
samples=samples.index_select(dim=-1, index=self._outcome_indices), X=X
)


@dataclass
class SubsetModelData:
model: Model
Expand Down Expand Up @@ -370,14 +385,25 @@ def get_botorch_objective_and_transform(
(optionally) a `PosteriorTransform`.
"""

if learned_objective_preference_model is not None:
objective = LearnedObjective(pref_model=learned_objective_preference_model)
return objective, None
# qLogProbabilityOfFeasibility uses constraints only, not objectives or
# posterior transforms.
if issubclass(botorch_acqf_class, qLogProbabilityOfFeasibility):
return None, None

if learned_objective_preference_model is not None:
# The model also predicts constraint-only outcomes. The preference model
# was trained on objective outcomes in model output order.
objective_mask = (objective_weights != 0).any(dim=0)
if not objective_mask.all():
return (
_SubsetLearnedObjective(
pref_model=learned_objective_preference_model,
outcome_indices=objective_mask.nonzero(as_tuple=True)[0],
),
None,
)
return LearnedObjective(pref_model=learned_objective_preference_model), None

if issubclass(
botorch_acqf_class,
(
Expand Down
4 changes: 4 additions & 0 deletions ax/storage/json_store/tests/test_json_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -1902,8 +1902,12 @@ def test_preference_optimization_config_with_pruning_target_json_roundtrip(
# Setup: create PreferenceOptimizationConfig with
# pruning_target_parameterization
pruning_target_parameterization = get_arm()
outcome_constraint = get_outcome_constraint(
metric=Metric(name="constraint_metric"), relative=False
)
preference_config = PreferenceOptimizationConfig(
objective=get_multi_objective(),
outcome_constraints=[outcome_constraint],
pruning_target_parameterization=pruning_target_parameterization,
preference_profile_name="default",
)
Expand Down
7 changes: 7 additions & 0 deletions ax/storage/sqa_store/tests/test_sqa_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -1612,11 +1612,15 @@ def test_preference_optimization_config_sqa_roundtrip(self) -> None:
)

test_test_profile = "test_profile_name"
outcome_constraint = OutcomeConstraint(
expression="m3 <= 0.5", metric_name_to_signature={"m3": "m3"}
)
for expect_relativized_outcomes in (True, False):
with self.subTest(f"{expect_relativized_outcomes=}"):
pref_config = PreferenceOptimizationConfig(
objective=multi_objective,
preference_profile_name=test_test_profile,
outcome_constraints=[outcome_constraint],
expect_relativized_outcomes=expect_relativized_outcomes,
)
experiment = Experiment(
Expand All @@ -1639,6 +1643,9 @@ def test_preference_optimization_config_sqa_roundtrip(self) -> None:
loaded_config.expect_relativized_outcomes,
expect_relativized_outcomes,
)
self.assertEqual(
loaded_config.outcome_constraints, [outcome_constraint]
)
loaded_objective = assert_is_instance(
loaded_config.objective, MultiObjective
)
Expand Down
Loading